<?php
/***************************************************************
*  Copyright notice
*
*  (c) 2010 Kasper Skårhøj <kaska@llab.dtu.dk>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * Plugin 'Enote Viewer' for the 'enotelms' extension.
 *
 * @author      Kasper Skårhøj <kaska@llab.dtu.dk>
 */

require_once(PATH_tslib.'class.tslib_pibase.php');

class tx_enotelms_pi1 extends tslib_pibase {
        var $prefixId = 'tx_enotelms_pi1';              // Same as class name
        var $scriptRelPath = 'pi1/class.tx_enotelms_pi1.php';   // Path to this script relative to the extension dir.
        var $extKey = 'enotelms';       // The extension key.
        var $pi_checkCHash = TRUE;

        var $eNoteTypeNames = array(0=>'eNoter', 1=>'Opgavesamling', 2=>'Quizzer', 3=>'Dagsordner');

        var $enoteHTMLpath = 'enotes/';
		var $enotePath = 'fileadmin/';
        var $atomUID = 34;

		var $ELAtom = '';
        
		var $hidableBoxEnvs = array('example' => 'eksempel','exercise'=>'opgave','bevis'=>'bevis');
		
		var $countHideMenus = 0;
        /**
         * The main method of the PlugIn
         *
         * @param       string          $content: The PlugIn content
         * @param       array           $conf: The PlugIn configuration
         * @return      The content that is displayed on the website
         */
		
        function main($content,$conf)   {
        		$this->conf=$conf;
                $this->pi_setPiVarDefaults();
                $this->pi_loadLL();
        
                        // Init pi_flexform / plugin configuration.
                $this->pi_initPIflexForm();
                
                # MIDLERTIDIG: TODO
                $GLOBALS['TSFE']->set_no_cache();       
                
				if($GLOBALS['TSFE']->loginUser) {
					$rec = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*','tx_enotelms_userdata','crfeuser_id='.intval($GLOBALS['TSFE']->fe_user->user['uid']));
					$this->userdata = $rec[0];
				}
				if($this->cObj->data['pi_flexform']['data']['sDEF']['lDEF']['showAdministrationInterface']['vDEF']) {
					$content .= $this->showErrorReports();
				} else {
                	/*        // Either render the list or single element:
	                if ($this->piVars['showUid'])   {       // If a single element should be displayed:
	                        $content = $this->renderNUIDlink($this->piVars['showUid']);
	                } elseif ($this->piVars['atom'])        {       // If a single element should be displayed:
	                        $content = $this->renderAtom($this->piVars['atom']);
	                } else {
	                        $content = $this->renderTOC();
	                }*/
            	    $content = $this->renderEnoteViewer();
				}
				$menuScript = '
				<script language="javascript" type="text/javascript">
				document.observe("dom:loaded", function() {
					if(window.pageYOffset) {
						s = window.pageYOffset;
					} else {
						s = document.documentElement.scrollTop;
					}
					
					if(s < 100) {
						newMenuOffset = 130 - s;
					} else {
						newMenuOffset = 30;
					}
					
			    	$$(".tx-enotelms-pi1-enoteMenu").first().style.top=newMenuOffset + "px";
					Event.observe(window, "scroll", function() {
						if(window.pageYOffset) {
							s = window.pageYOffset;
						} else {
							s = document.documentElement.scrollTop;
						}
						if(s < 100) {
							newMenuOffset = 130 - s;
						} else {
							newMenuOffset = 30;
						}
				    	$$(".tx-enotelms-pi1-enoteMenu").first().style.top=newMenuOffset + "px";
					});
					if(window.innerWidth < 970 || document.documentElement.offsetWidth < 970) {
						$$("div.tx-enotelms-pi1-enoteMenu").first().style.display="none";
						$$("div.tx-enotelms-pi1-singleView").first().style.cssFloat="left";
						$$("div.tx-enotelms-pi1-singleView").first().style.styleFloat="left";
						$$("div.tx-enotelms-pi1-singleView").first().style.margin="20px";
					}
					Event.observe(window, "resize", function e(){
						if(window.innerWidth < 970 || document.documentElement.offsetWidth < 970) {
							$$("div.tx-enotelms-pi1-enoteMenu").first().style.display="none";
							$$("div.tx-enotelms-pi1-singleView").first().style.styleFloat="left";
							$$("div.tx-enotelms-pi1-singleView").first().style.cssFloat="left";
							$$("div.tx-enotelms-pi1-singleView").first().style.margin="20px"
						} else if(window.innerWidth >= 970 || document.documentElement.offsetWidth >= 970) {
							$$("div.tx-enotelms-pi1-enoteMenu").first().style.display="";
							$$("div.tx-enotelms-pi1-singleView").first().style.cssFloat="right";
							$$("div.tx-enotelms-pi1-singleView").first().style.styleFloat="right";
							$$("div.tx-enotelms-pi1-singleView").first().style.margin="";
						}
					});
				});
				</script>
				';
				$content = $menuScript . $content;
				return $this->pi_wrapInBaseClass($content);
        	
}
        function renderEnoteViewer() {
			$content = '';
	        if ($this->piVars['showUid'])   {       // If a single element should be displayed:
                    $mainContent = $this->renderNUIDlink($this->piVars['showUid']);
					$uid = $this->piVars['showUid'];
            } elseif ($this->piVars['atom'])        {       // If a single element should be displayed:
					$this->ELAtom = $this->getELAtomFromUid($this->piVars['atom']);
					$record = $this->getAtomType($this->ELAtom['url']);
                    $mainContent =  $this->renderAtom($this->piVars['atom']);
					$uid = $record['NUID'];
            } else { // Render the track selector
                    $content = $this->renderFavorites() . '<div' . $this->pi_classparam('singleView') . ' style="width:100%">'.$this->renderTOC().'</div>';
            }
			if(!$content) {
				preg_match('/^NUID(\d+)-?(((IDX)?(\d+)?)(.+)?)?/',$uid,$match);
				$content = $this->renderMenu($match[1],$match[5],$match[2]) . "<div".$this->pi_classparam('singleView').">" . $mainContent . "</div>";
			}
			return $content;
		}
		function renderMenu($uid,$idx,$parameter) {
			if($GLOBALS['TSFE']->loginUser) {
				$theURL = "materialer/enoter/afsnit/NUID" . $uid . ($parameter?"-" . $parameter:'') . "/";
				$ELOinfo = $this->getELAtom($theURL, false);
			}
			$htmlParser = t3lib_div::makeInstance('t3lib_parsehtml'); 
			$fileArr = t3lib_div::get_dirs(t3lib_div::getFileAbsFileName($this->enoteHTMLpath));
			if(in_array($uid,$fileArr)) {
				$data = unserialize(t3lib_div::getUrl(t3lib_div::getFileAbsFileName($this->enoteHTMLpath).$uid.'/index.html.ser'));
				if($data['eNoteRec']['type']==0) { // Enote, vis oversigsmenu med sektioner
					if(is_array($data)) {
						$title = $htmlParser->prefixResourcePath($this->enoteHTMLpath.$uid.'/',$data['eNoteRec']['title']);
						//$content .= "<h2>" . $title . "</h2>";
						//$content .= "<ul style='padding: 0; list-style-type: none'>";
						$content .= '<div class="webpart"><div class="topbar"><span class="topBarTitle">Indhold</span></div><div class="inner"><div style="margin: 10px;">';
						foreach($data['structure']['documentParts'] as $index => $part) {
							if($part['HeaderLevel'] == 1) {
								$headerText = $htmlParser->prefixResourcePath($this->enoteHTMLpath.$uid.'/',$part['HeaderText']);
								$match = preg_split("/(\d+\.)+/",$headerText,2);
								$linkText = implode('',$match);
						
								
								//$linkText = $headerText;
								//if($GLOBALS['TSFE']->loginUser) {
								//	$theURL = "materialer/enoter/afsnit/NUID" . $uid . ($index?'-IDX'.$index:'') . "/";
								//	$ELOinfo = $this->getELAtom($theURL);
								//	$content .= '<li class="'.($ELOinfo['userdata'][0]['done']?'menu-item-read':'menu-item-unread').($index == $idx?' act':'').'"><span>'.$this->pi_linkTP_keepPIvars($linkText,array('atom'=>$ELOinfo['uid']),1) . '</span></li>';
								//} else {
									//$link = split('\?',$this->pi_list_linkSingle($linkText,'NUID'.$uid.'-IDX'.$index,1,0,1));
									if(!$parameter || array_key_exists('NUID'.$uid.'-'.$parameter,$data['structure']['documentParts'][1]['labelsInside'])) {
										//$link = "<a href='".$_SERVER['REQUEST_URI']."#".$part['HTML:id']."'>". $linkText . "</a>";
										$link = "<a href='javascript:void(0)' onClick='Effect.ScrollTo(\"".$part['HTML:id']."\")' class='submenuitem' onfocus='blurLink(this);'>".$linkText."</a>";
									} else {
										$link = preg_split('/\?/',$this->pi_list_linkSingle('','NUID'.$uid,1,0,1));
										$link = '<a href="'.$link[0]. "#" . $part['HTML:id'].'" onfocus="blurLink(this);" class="submenuitem">'.$linkText.'</a>';
									}
									//$content .= '<li class="menu-item-unread'.($index == $idx?' act':'').'"><span>'.$link.'</span></li>';
									$content .= '<div style="border-bottom: 1px solid rgb(231, 235, 239); padding: 1px 0px 5px;"><img src="fileadmin/templates/portalen_gray_files/arrow_purple.png" alt="" style="float: left; margin-top: 4px; margin-right: 4px;" /><div style="margin-left: 8px;">'.$link.'</div></div>';
								//}
							}
						}
						//$content .= "</ul>";
						$content .= "</div></div></div><br/><br/>";
						$content .= '<div class="webpart"><div class="topbar"><span class="topBarTitle">Hop til eNote</span></div><div class="inner"><div style="margin: 10px;">';
						$enotes = $this->getENotes();
						$content .= "<select style='width:100%' onChange='location.href=this.value'><option selected='selected'>Vælg eNote ...</option>";
						foreach($enotes[0] as $idx => $enoteData) {
						    $nuid = key($enoteData['structure']['documentParts'][1][labelsInside]);
	                        if(strlen($uid) == 0) {
	                        	$nuid = 'NUID'.$enoteData['eNoteRec']['uid'];
	                        }
							$enoteData['eNoteRec']['title'] = $htmlParser->prefixResourcePath($this->enoteHTMLpath.$enoteData['eNoteRec']['uid'].'/',$enoteData['eNoteRec']['title']);
			                $enoteData['eNoteRec']['title'] = str_replace('Chapter','',$enoteData['eNoteRec']['title']);
							list($link) = explode('?',$this->pi_list_linkSingle('',$nuid,1,0,1));
							$content .= "<option value='".$link."'>eNote ".$idx . ": " . $enoteData['eNoteRec']['title'] . "</option>\n";
						}
						$content .= "</select></div></div></div><br/><br/>";

						// Display PDF link if user is logged in...
						if($GLOBALS['TSFE']->loginUser) {
							$link = "<a href='" . $this->enotePath . $data['eNoteRec']['directory'] . "/" . str_replace('.tex','.pdf',$data['eNoteRec']['texfile']) . "'>Download som PDF</a>";	
							$content .= '<div class="webpart"><div class="topbar"><span class="topBarTitle">Muligheder</span></div><div class="inner"><div style="margin: 10px;">';
							$content .= '<div style="border-bottom: 1px solid rgb(231, 235, 239); padding: 1px 0px 5px;"><img src="fileadmin/templates/portalen_gray_files/arrow_purple.png" alt="" style="float: left; margin-top: 4px; margin-right: 4px;" /><div style="margin-left: 8px;">'.$link.'</div></div>';
							$content .= "</div></div></div>";
						}
					}
				}
			}

			// Kommer brugeren fra en dagsorden?
			if($GLOBALS['TSFE']->loginUser && (( $this->piVars['returnUrl']) || ($data['eNoteRec']['type'] == 3))) {
				//$content2 .= "<div style='display: ".($_SERVER['REMOTE_ADDR'] == '82.211.215.27'?'':'none')."'>";
				preg_match("/\[showUid\]=NUID(\d+)-IDX(\d+)/",urldecode($this->piVars['returnUrl']),$match);
				if($data['eNoteRec']['type'] == 3) {
					$nuid =  $this->piVars['showUid'];
				} else {
					$nuid = "NUID" . $match[1] . "-IDX".$match[2];
				}
				$content2 .= $this->getActiveElements($nuid);
				//$content2 .= "</div>";
			}
			/*if($content && !$content2) {
				$finalContent = $content;
			} elseif(!$content && $content2) {
				$finalContent = $content2 . "</div>";
			} else {
				$finalContent = $content2 . "<br/><br/>" .  $content;
			}*/
			$content = '<!--googleoff: snippet--><div' . $this->pi_classparam('enoteMenu') . '>' . $content2 . $content . '</div><!--googleon: snippet-->';
			return $content;
		}
		function getENotes() {
			$fileArr = t3lib_div::get_dirs(t3lib_div::getFileAbsFileName($this->enoteHTMLpath));
            $noteUIDs = t3lib_div::intExplode(',',$this->cObj->data['pi_flexform']['data']['sDEF']['lDEF']['showUID']['vDEF']);

            $enotes = array('0'=>array());
            foreach($fileArr as $dir)       {
                    if (in_array($dir,$noteUIDs) || !trim($this->cObj->data['pi_flexform']['data']['sDEF']['lDEF']['showUID']['vDEF']))     {
                            $data = unserialize(t3lib_div::getUrl(t3lib_div::getFileAbsFileName($this->enoteHTMLpath).$dir.'/index.html.ser'));
                            if (is_array($data))    {
                                    if ($data['eNoteRec']['type']==0)       {
                                            $enotes[$data['eNoteRec']['type']][$data['eNoteRec']['enote']] = $data;
                                    } else {
                                            $enotes[$data['eNoteRec']['type']][] = $data;
                                    }
                            } else debug( $dir);
                    }
            }
            ksort($enotes);
            ksort($enotes[0]);
			return $enotes;
		}
        function renderTOC() {
                $enotes = $this->getENotes();
                $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');       
                
                
                $output = '';
                foreach($enotes as $eNoteType => $enotesInside) {
                        $output.='<h1 class="csc-firstHeader">'.$this->eNoteTypeNames[$eNoteType].'</h1>';
                        
                        $output.='<table id="enotes_toc" style="width:100%"><tr><th align="left" style="width: 100%">Titel</th><th align="right">Sidst&nbsp;redigeret</th><th></th></tr>';
                        foreach($enotesInside as $idx => $enoteData)    {
                                $enoteData['eNoteRec']['title'] = $htmlParser->prefixResourcePath($this->enoteHTMLpath.$enoteData['eNoteRec']['uid'].'/',$enoteData['eNoteRec']['title']);
                                $enoteData['eNoteRec']['title'] = str_replace('Chapter','',$enoteData['eNoteRec']['title']);
                                
                                // TODO: THIS ASSUMES THAT ENOTES REFERENCED FROM AGENDAS IS IDENTIFIED BY THE FIRST LABEL
                                // e.g. NUID17-tn1
                                $uid = key($enoteData['structure']['documentParts'][1][labelsInside]);
                                if(strlen($uid) == 0) {
                                	$uid = 'NUID'.$enoteData['eNoteRec']['uid'];
                                }
                                $atom = $this->getELAtom(strtok($this->pi_list_linkSingle('',key($enoteData['structure']['documentParts'][1][labelsInside]),1,0,1), "?"), false);
                                if($atom && $GLOBALS['TSFE']->loginUser) {
                                	$userdataImages = '<img src="typo3conf/ext/enotelms/icons/done'.(!$atom['userdata'][0]['done']?'_d':'').'.png" width="20" height="24" align="absmiddle"/><img src="typo3conf/ext/enotelms/icons/heart'.(!$atom['userdata'][0]['fav']?'_d':'').'.png" width="20" height="12" align="absmiddle" />&nbsp;&nbsp;';
                                }
								$output.="<tr>";
                                $output.='<td>'.$userdataImages . $this->pi_list_linkSingle($idx.': '.$enoteData['eNoteRec']['title'],$uid,1).'</td><td align="right"><span style="font-size:80%; color: #666666; font-style:italic; padding-left: 20px;">'.str_replace(' ',"&nbsp;",strftime('%e. %B %Y',$enoteData['eNoteRec']['lastgeneratedflag'])).'</span></td><td><a href="javascript:void(0)" class="unfold_sub">Fold&nbsp;ud</a></td>';
                                $output.='</tr><tr><td colspan="3" style="display:none"><ul>';
                                foreach($enoteData['structure']['documentParts'] as $partIdx => $partContent)   {
                                        if ($partContent['HeaderText']) {

                                                $label = key($partContent['labelsInside']);
                                                if(!$label)     {$label = 'NUID'.$enoteData['eNoteRec']['uid'].'-IDX'.$partIdx;}

                                                $partContent['HeaderText'] = $htmlParser->prefixResourcePath($this->enoteHTMLpath.$enoteData['eNoteRec']['uid'].'/',$partContent['HeaderText']);
                                                $partContent['HeaderText'] = str_replace('Chapter','',$partContent['HeaderText']);
                                                $output.='<li><a href="'.$this->pi_list_linkSingle('',$uid,1,0,1).'#'.$partContent['HTML:id'].'">'.$partContent['HeaderText'].'</a></li>';         // TODO: Set level correctly!: $partContent['HeaderLevel'].' - '.
                                        }
                                }
                                $output.='</ul></td></tr>';
                        }
                        $output.='</table>';
						$output.='<script language="javascript" type="text/javascript">
						$$(".unfold_sub").each(function(e){
							Event.observe(e,"click",function(){
								u = e.up("tr").next().down();
								Effect.toggle(u);
							})
						});
						</script>';
                }
                
                return $output;
        }
        function renderFavorites() {
        	$output = '';
        	if($GLOBALS['TSFE']->loginUser) {

        		$favorites = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*','tx_enotelms_atom_userdata','fav>0 AND crfeuser_id='.intval($GLOBALS['TSFE']->fe_user->user['uid']),'','fav DESC',50);

        		$output .= "<div style='overflow: hidden' " . $this->pi_classparam('favorites') . ">";
        		$output.='<h1 class="csc-firstHeader">Favoritter</h1>';
        		if(count($favorites) == 0) {
        			$output .= "<div style='border: 1px solid #ccc; background-color: rgb(251,244,114); padding: 6px; margin-bottom: 10px; font-weight: bold'>Du har ikke markeret nogle læringsobjekter som “favoritter” endnu.</div>";
        		} else {
        			/*$fav = array();
	        		foreach($favorites as $item) {
	        			$record = $this->getELAtomFromUid($item['atom_id']);
	        			$type = $this->getAtomType($record['url']);
	        			if($record['userdata'][0]['refererID']) {
	        				$referer = $record['userdata'][0]['refererID'];
	        			} elseif($record['refererID']) {
	        				$referer = $record['refererID'];
	        			} else {
	        				$referer = 0;
	        			}
	        			if(!isset($fav[$referer])) {
	        				$fav[$referer] = array();
	        			}
						$parts = preg_split("/\//", $record['url']);
						$element = $record['title'];
						//$element = $this->getAtomTitle($record['url']);
	        			$fav[$referer][] = array("title" => $element, "record" => $record);
	        		}
	        		
	        		foreach($fav as $ID => $f) {
	        			if($ID === 0) {
	        				$title = "Uden reference";
	        			} else {
	        				$title = $this->getAtomTitle("materialer/enoter/afsnit/" . $ID . "/");
	        			}
	        			$output .= "<b>" . $title . "</b><p>";
	        			foreach($f as $element) {
	        				$output .=  $element['title'] . "<br/>";
	        			}
	        			$output .= "</p>";
	        		}*/
	        		
	        		$presentable = array(
	        				"pencast" => "Pencasts",
	        				"mapledemo" => "MapleDemoer",
	        				"exercise" => "Opgaver",
	        				"video" => "Videoer"
	        			);
	        		$colors = array(
	        				"exercise" => "#F90",
	        				"mapledemo" => "#C00",
	        				"pencast" => "rgb(76,166,76)",
	        				"video" => "rgb(147,75,147)"
	        			);
	        		
	        		$fav = array("exercise" => array(), "pencast" => array(), "mapledemo" => array(), "video" => array());
	        		foreach($favorites as $item) {
	        			$record = $this->getELAtomFromUid($item['atom_id']);
	        			$t = $this->getAtomType($record['url']);
	        			$type = $t['type'];
						if($type == 'enote') {
							preg_match("/^NUID(\d+)/",$t['NUID'],$matches);
							$data = unserialize(t3lib_div::getUrl(t3lib_div::getFileAbsFileName($this->enoteHTMLpath).$matches[1].'/index.html.ser'));
							if($data['eNoteRec']['type'] == 1) {
								$type = "exercise";
								preg_match("/^(Opgave\ \d+:\ )?(.+)/is",$record['title'], $match);
								$record['title'] = $match[2];
							}
						}

	        			if($record['userdata'][0]['refererID']) {
	        				$referer = $record['userdata'][0]['refererID'];
	        			} elseif($record['refererID']) {
	        				$referer = $record['refererID'];
	        			} else {
	        				$referer = 0;
	        			}
	        			if(array_key_exists($type, $presentable)) {
		        			if(!isset($fav[$type])) {
		        				$fav[$type] = array();
		        			}
							$parts = preg_split("/\//", $record['url']);
							$element = $record['title'];
							//$element = $this->getAtomTitle($record['url']);
							//echo $this->pi_linkTP('',Array($this->prefixId=>array("showUID"=>$referer)),0) . "<br />";
							if($referer !== 0) {
								$returnUrl = "/2011/materialer/enoter/?tx_enotelms_pi1[showUid]=" . $referer;
							} else {
								$returnUrl = '';
							}
							$element = $this->pi_linkTP($element, Array($this->prefixId=>array('atom'=>$record['uid'], 'returnUrl' => $returnUrl)), 1);
		        			$fav[$type][] = array("title" => $element, "record" => $record);
	        			}
	        		}
	        		$output .= "<div style='margin: 10px 0 10px 0; overflow: hidden'>";
	        		foreach($fav as $ID => $f) {
	        			$output .= "<div style='width: 23%; float: left; padding-bottom: 1000px; margin-bottom: -1000px; padding-left: 5px; border-left: 7px solid ".$colors[$ID]."'><h4 style='padding-top: 0; margin-top: 0; '><div style='border-color: ".$colors[$ID]."' class='box-title-lines'><div style='border-color: ".$colors[$ID]."'>&nbsp;</div></div>&nbsp;" . $presentable[$ID] . "</h4><p style='padding-left:5px'>";
	        			foreach($f as $element) {
	        				$output .=  "<span style='display: block; padding-bottom: 6px'>".$element['title'] . "</span>";
	        			}
	        			$output .= "</p></div>";
	        		}
	        		$output .= "<div style='clear: both'></div></div></div>";
        		}
        	}
        	return $output;
        }
        function getEnoteInfo($uid) {

        }
        function showErrorReports() {
			$postData = t3lib_div::_POST('tx_enotelms_pi1');
			if($postData['resolved'] || $postData['noterror'] || $postData['unresolved'] || $postData['willnotfix']) {
				$atom_resolved = implode(',',t3lib_DB::cleanIntArray(array_keys($postData['atom_action'])));
				$comment_resolved = implode(',',t3lib_DB::cleanIntArray(array_keys($postData['comment_action'])));
				if($postData['resolved']) {
					$resolvedCode = 1;
				} else if ($postData['noterror']) {
					$resolvedCode = 2;
				} else if($postData['unresolved']) {
					$resolvedCode = 0;
				} else if($postData['willnotfix']) {
					$resolvedCode = 3;
				}

				
				$field_values = array(
					'resolved_date' => time(),
					'resolved_error' => $resolvedCode
				);
				/*if($atom_resolved)
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_enotelms_atom_comment','atom_id IN (' . $atom_resolved . ')', $field_values); */
				if($comment_resolved)
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_enotelms_atom_comment','uid IN ('. $comment_resolved.')', $field_values);
			}
			

			$content = "<h3>Ubehandlede fejl</h3>\n".$this->errorReportTable('unresolved');
			$content .= "<br/><h3>Behandlede fejl</h3>\n".$this->errorReportTable('resolved');
			return $content;
		}
		
		function errorReportTable($mode) {
			
			// Allow group_concat() to have unlimited length
			$GLOBALS['TYPO3_DB']->sql_query('SET SESSION group_concat_max_len=18446744073709547520');
			
			// Huge non-selfexplanatory SQL query
			$rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('atom_id, group_concat(resolved_error order by tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').' DESC) as resolved_error,group_concat(resolved_date order by tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').' DESC) as resolved_date, group_concat(tx_enotelms_atom_comment.uid order by tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').' DESC) as uid, tx_enotelms_atom.title as title, group_concat(tx_enotelms_atom_comment.crdate order by tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').' DESC) as crdate, group_concat(replace(comment,",","&#44;") order by tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').' DESC) as comment, group_concat(fe_users.email order by tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').' DESC) as email, group_concat(tx_enotelms_atom_comment.name order by tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').' DESC) as name','tx_enotelms_atom_comment,tx_enotelms_atom,fe_users','reported_error=1 AND '.($mode=='resolved'?'resolved_error>0 AND':'').' atom_id = tx_enotelms_atom.uid AND tx_enotelms_atom_comment.crfeuser_id = fe_users.uid','atom_id','max(tx_enotelms_atom_comment.'.($mode=='resolved'?'resolved_date':'crdate').') DESC');
			$content = '<form action="'.t3lib_div::getIndpEnv('REQUEST_URI').'" method="POST">';
			$content .= '<input type="hidden" name="no_cache" value="1">';
			$content .= '<table class="error-report">
							<tr class="error-table-header">
								<th>Atom</th>
								<th style="width: 100%">Kommentar</th>
								<th>Fejlmelding</th>';
			if($mode == 'resolved') {
				$content .= '	<th>Tilbagemelding</th>
								<th>Status</th>';
			}
			$content .= '
								<th></th>
							</tr>';
			foreach($rows as $id => $row) {
				$names = explode(',',$row['name']);
				$emails = explode(',',$row['email']);
				$comments = explode(',',$row['comment']);
				$crdates = explode(',',$row['crdate']);
				$uids = explode(',',$row['uid']);
				$resolved = explode(',',$row['resolved_error']);
				$resdate = explode(',',$row['resolved_date']);
				if((array_sum($resolved) && $mode == 'resolved') || ($mode == 'unresolved' && in_array(0,$resolved))) {
					$content .= '<tr class="atom_header"><td><a target="_blank" href="/2011/materialer/enoter/atom/' . $row['atom_id'] . '">'.$row['atom_id'].'</a></td><td>&nbsp;'./*$row['title'].*/'</td><td>&nbsp;'./*strftime('%d/%m/%Y %R',end($crdates)).*/'</td>'.($mode == 'resolved' ? '<td></td><td></td>' : '').'<td><input type="checkbox" name="'.$this->prefixId.'[atom_action]['.$row['atom_id'].']" onClick="c=(this.checked?1:0);$(this).up(\'table\').select(\'input.checkbox_atom_'.$row['atom_id'].'\').each(function(e){e.checked=c});"></input></td></tr>';
					$count = 0;
					foreach($uids as $key => $uid) {
						
						if($mode == 'resolved') {
							if($resolved[$key] == '1') {
								$resolvedStatus = '<span style="color: green">Fejl&nbsp;rettet</span>';
							} else if($resolved[$key] == '2') {
								$resolvedStatus = '<span style="color: #323586">Ikke&nbsp;en&nbsp;fejl</span>';
							} else if($resolved[$key] == '3') {
								$resolvedStatus = '<span style="color: #ff6600">Rettes&nbsp;ikke</span>';
							} else {
								$resolvedStatus = '';
								continue; // Issue is NOT resolved
							}
						} else if ($mode == 'unresolved' && $resolved[$key]) {
							continue; // Issue IS resolved
						}
					
						$content .= '<tr class="'.(++$count%2?'':'odd').'"><td></td><td>' . nl2br(htmlspecialchars(trim(str_replace('&#44;',',',$comments[$key])))) . '</td><td>'.str_replace(" ","&nbsp;",strftime('%d/%m/%Y %R',$crdates[$key])).'</td>'.($mode == 'resolved' ? '<td>' . str_replace(' ','&nbsp;',strftime('%d/%m/%Y %R',$resdate[$key])) . '</td>'.'<td>'.($resolvedStatus).'</td>' : '') . '<td><input type="checkbox" name="'.$this->prefixId.'[comment_action]['.$uids[$key].']" class="checkbox_atom_'.$row['atom_id'].'"></input></td></tr>';
					}
				}
				
			}
			$content .= "</table><br/><div style='float:right'>".($mode=='resolved'?'<input type="submit" name="'.$this->prefixId.'[unresolved]" value="Marker som uløst"></input>':'')."<input type='submit' name='".$this->prefixId."[resolved]' value='Fejlen er rettet'></input><input type='submit' name='".$this->prefixId."[noterror]' value='Ikke en fejl'></input><input type='submit' name='".$this->prefixId."[willnotfix]' value='Rettes ikke'></input></div>
			</form>";
			
			return $content;
		}
        function renderAtom($uid)       {
                if ($GLOBALS['TSFE']->loginUser)        {
                        
                        $record = $this->getELAtomFromUid($uid);
                        if (!is_array($record)) return;
#debug($record);
                        $postData = t3lib_div::_POST('tx_enotelms_pi1');

                        $field_values['lastVisited'] = time();
                        if (is_array($postData))        {

                                        // Personal stuff:
                                $field_values = array();
                                if ($postData['saveNotes'])     { $field_values['note'] = $postData['notes']; }
                                if ($postData['done'])  { $field_values['done'] = time(); }
                                if ($postData['undone'])        { $field_values['done'] = 0; }
                                if ($postData['fav'])   {
                                	$field_values['fav'] = time(); 
                                	if(preg_match("/NUID(\d+)-IDX(\d+)/",$this->piVars['returnUrl'], $matches)){
					                	$NUID = $matches[1];
					                	$IDX  = $matches[2];
					                }
			                        if($NUID && $IDX) {
			                        	$field_values['refererID'] = 'NUID' . $NUID . '-IDX' . $IDX;
			                        }
                                }
                                if ($postData['unfav']) { 
                                	$field_values['fav'] = 0; 
                                	$field_values['refererID'] = '';
                                }
                                
                                        // Comments:
                                if ($postData['saveComment'])   {
                                        $field_values = array(
                                                'comment' => $postData['comment'],
                                                'rating' => $postData['rating'],
                                                'atom_id' => $record['uid'],
                                                'crfeuser_id' => $GLOBALS['TSFE']->fe_user->user['uid'],
                                                'crdate' => time(),
                                                'name' => $GLOBALS['TSFE']->fe_user->user['name'],
                                                'username' => $GLOBALS['TSFE']->fe_user->user['username'],
												'reported_error' => ($postData['report_error']?1:0)
                                        );
                                        $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_enotelms_atom_comment',$field_values);
										

                                }
                        }
                        if (count($field_values))       {
                            if (!$record['userdata'])       {
                                    $field_values['crfeuser_id'] = $GLOBALS['TSFE']->fe_user->user['uid'];
                                    $field_values['atom_id'] = $record['uid'];
                                    $GLOBALS['TYPO3_DB']->exec_INSERTquery('tx_enotelms_atom_userdata',$field_values);
                            } else {
                                    $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_enotelms_atom_userdata','atom_id='.intval($record['uid']).' AND crfeuser_id='.intval($GLOBALS['TSFE']->fe_user->user['uid']),$field_values);
                            }
                        }
                            # Re-read record:
                        $record = $this->getELAtomFromUid($uid);
                        
                                // Video:
                        $content='';
                        $atomType = $this->getAtomType($record['url']);
                        switch($atomType['type'])       {
                                case 'video':
                                        $metaData = $this->getMetaData($atomType['localFile']);
                                        if (is_array($metaData))        {
                                                $content = '<h2>'.htmlspecialchars($metaData['title']).'</h2>
                                                        <p>'.htmlspecialchars($metaData['description']).'</p>
                                                        ';

                                                if ($metaData['enotelms:YouTubeUID'])   {
                                                        $content.= '
                                                        <object width="640" height="385">
                                                                <param name="movie" value="http://www.youtube.com/v/'.$metaData['enotelms:YouTubeUID'].'?fs=1&amp;hl=en_US&ap=%2526fmt%3D18"></param>
                                                                <param name="allowFullScreen" value="true"></param>
                                                                <param name="allowscriptaccess" value="always"></param>
                                                                <embed src="http://www.youtube.com/v/'.$metaData['enotelms:YouTubeUID'].'?fs=1&amp;hl=en_US" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed>
                                                        </object>
                                                        ';
                                                        $content.='
                                                        <p><em>Dato: '.htmlspecialchars(strftime('%d/%m/%Y %R',$metaData['pubDate'])).'</em></p>
                                                        <p><a href="http://www.youtube.com/watch?v='.$metaData['enotelms:YouTubeUID'].'" target="_blank">Gå til YouTube kanal</a></p>';
                                                }
                                        }
                                break;
                                case 'enote':
                                        $content = $this->renderNUIDlink($atomType['NUID'], false);
                                break;
								case 'pencast':
									$cookie = tempnam ("/tmp", "CURLCOOKIE");
									$ch = curl_init();
									curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
									curl_setopt( $ch, CURLOPT_URL, $record['url']);
									curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
									curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
									curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
									curl_setopt( $ch, CURLOPT_FAILONERROR, true);
									$result = curl_exec( $ch );
									curl_close ( $ch );
									if($result) {
										$livescribe = new DOMDocument();
										$livescribe->loadHTML($result);
										$link = $livescribe->getElementsByTagName('link');
										$meta = $livescribe->getElementsByTagName('meta');
										foreach($link as $l) {
											if($l->getAttribute("rel") == 'video_src') {
												$xmllink = $l->getAttribute('href');
											}
										}
										foreach($meta as $m) {
											$name = $m->getAttribute('name');
											if($name == 'title') {
												$title = $m->getAttribute('content');
											} elseif($name == 'description') {
												$desc = $m->getAttribute('content');
												if(!trim($desc)) {$desc = "<span style='color:#ccc'>(Ingen beskrivelse)</span>";}
											}
										}
									}
									unlink($cookie);
									$linkparts = preg_split('/=/',$record['url']);
									$parts = preg_split('/path/',$xmllink);
									
									if($xmllink && $parts[1]) {
									//$content = '<div class="pencast"><a href="'.$record['url'].'" target="_blank">'.$title.'</a><br /><small>brought to you by <a href="http://www.livescribe.com/" target="_blank">Livescribe</a></small><br /><object width="456" height="632"><param name="movie" value="http://www.livescribe.com/media/swf/embedPlayer.swf"></param><param name="FlashVars" value="path'.$parts[1].'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'.$link.'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="456" height="632"></embed></object></div>';
									$content = '<br/><h1 class="csc-firstHeader">Pencast: '.$title.'</h1><small>brought to you by <a href="http://www.livescribe.com/" target="_blank">Livescribe</a></small><br /><div class="pencast" style="float:left"><object width="456" height="632"><param name="movie" value="http://www.livescribe.com/media/swf/embedPlayer.swf"></param><param name="FlashVars" value="path'.$parts[1].'"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'.$xmllink.'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="456" height="632"></embed></object></div><div style="float:left; width:224px; padding: 10px"><h4>Beskrivelse:</h4>'.$desc.'<h4>PDF-version</h4><a href="http://www.livescribe.com/cgi-bin/WebObjects/LDApp.woa/wa/downloadPDF?sid='.end($linkparts).'">Link</a></div>';
									}
								break;
								/*case 'mapledemo':
									//header("Content-Type: application/x-maple");
									echo file_get_contents("http://01005.mat.dtu.dk/2011/".$record['url']);
									//header("Location: " . $record['url']);
								break;*/
                                default:
                                        debug($atomType['type'],'type');
                                break;
                        }

                                // HTML embed:
                        if (trim($record['HTML']) && !trim($content))      {
                                $content.= $record['HTML'];
                        }
                        
                                // Default:
                        if (!trim($content))    {
                                        $content = '<h2>E-læringsaktivitet:</h2>
                                                <a href="'.htmlspecialchars($record['url']).'" target="_blank">Åben aktiviteten "'.htmlspecialchars($record['title']).'" i et nyt vindue</a>';
                        }

                        $content.='<div style="clear:both">
                        <br/><br/>
                        <form action="'.t3lib_div::getIndpEnv('REQUEST_URI').'" method="POST">
                                <input type="hidden" name="no_cache" value="1">
                                
                                <table border="0" style=" width:700px;"><tr><td valign="top">
                                <p style="font-size:10px;">Egne noter til aktiviteten:</p>
                                <textarea cols="30" rows="5" name="'.$this->prefixId.'[notes]">'.t3lib_div::formatForTextarea($record['userdata'][0]['note']).'</textarea>
                                
                                <input type="submit" name="'.$this->prefixId.'[saveNotes]" value="Gem">
                                </td><td valign="top">
                                <img src="typo3conf/ext/enotelms/icons/done'.(!$record['userdata'][0]['done']?'_d':'').'.png" width="20" height="24" align="absmiddle"/>'.
                                        (!$record['userdata'][0]['done'] ? '<input type="submit" name="'.$this->prefixId.'[done]" value="Afkryds" />' : '<input type="submit" name="'.$this->prefixId.'[undone]" value="Fjern afkrydsning" />').'
                        <br><img src="typo3conf/ext/enotelms/icons/heart'.(!$record['userdata'][0]['fav']?'_d':'').'.png" width="20" height="12" align="absmiddle" />'.
                                        (!$record['userdata'][0]['fav'] ? '<input type="submit" name="'.$this->prefixId.'[fav]" value="Favorit" />' : '<input type="submit" name="'.$this->prefixId.'[unfav]" value="Fjern favorit" />').'
                                        </td></tr></table>
                        </form></div>';
                
                
                        // Vis kommentarer:
                        $commentsForAtom = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*','tx_enotelms_atom_comment','atom_id='.intval($record['uid']),'','crdate DESC',50);
                        $commentsHTML = '';
                        $accumRating = 0;
                        $accumCount = 0;
                        foreach($commentsForAtom as $comment)   {
								$commentMessage = '';
                                $commentsHTML.='
                                <tr style="background-color: #eeeeee;">
                                        <td><p style="font-size:10px"><b>'.htmlspecialchars($comment['name']).'</b> - <em>'.htmlspecialchars($comment['username']).'</em></p></td>
                                        <td align="right"><p style="font-size:10px">'.strftime('%d/%m/%Y %R',$comment['crdate']).'<img src="typo3conf/ext/enotelms/icons/stars-'.$comment['rating'].'.png" width="64" height="12" align="absmiddle" />'.'</p></td>
                                </tr>
                                <tr style="background-color: transparent;">
                                        <td colspan="2">'.nl2br(htmlspecialchars(trim($comment['comment']))).'</td>
                                </tr>';
								if($comment['reported_error'] && !$comment['resolved_error']) {
									$commentMessage = "<span style='color: red' class='comment_error'>Denne kommentar er indberettet som en fejl i ovenstående aktivitet.</span>";
								} elseif($comment['reported_error'] && $comment['resolved_error']) {
									switch($comment['resolved_error']) {
										case '1':
											$commentMessage = "<span style='color: green' class='comment_error'>Fejlen indberettet i denne kommentar er rettet. (".strftime('%d/%m/%Y %R',$comment['resolved_date']).")</span>";
										break;
										case '2':
											$commentMessage = "<span style='color: #323586' class='comment_error'>Det indberettede betragtes ikke som en fejl. (".strftime('%d/%m/%Y %R',$comment['resolved_date']).")</span>";
										break;
										case '3':
											$commentMessage = "<span style='color: #ff6600' class='comment_error'>Fejl anerkendt, men kan ikke rettes. (".strftime('%d/%m/%Y %R',$comment['resolved_date']).")</span>";
										break;
									}
								}
								if($commentMessage) {
									$commentsHTML .= '<tr style="background-color: transparent;">
			                                <td colspan="2" style="padding-bottom:10px;">'.$commentMessage.'</td>
			                        </tr>';
								}
                                if ($comment['rating']>0)       {
                                        $accumRating+=$comment['rating'];
                                        $accumCount++;
                                }
                        }
                        $content.='<h3>Kommentarer:</h3><table border="0" cellpadding="0" cellspacing="0" style=" width:700px;">'.$commentsHTML.'</table>';
#                       $content.=t3lib_div::view_array($commentsForAtom);
                
                        if ($accumCount>0)      {
                                $storeRating = round($accumRating*10/$accumCount);
                                if ($record['accumulated_rating']!=$storeRating)        {
                                        $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_enotelms_atom','uid='.intval($record['uid']),array('accumulated_rating'=>$storeRating));
                                }
                        }
                
                
                        // Indtast Kommentarer:
                        $content.='
                        <form action="'.t3lib_div::getIndpEnv('REQUEST_URI').'" method="POST">
                                <input type="hidden" name="no_cache" value="1">
                                
                                <p style="font-size:10px; background-color: #cccccc; width:700px;">Din kommentar:</p>
                                <textarea cols="45" rows="5" name="'.$this->prefixId.'[comment]"></textarea><br>
                                
                                <p style="font-size:10px;">Din vurdering (1-5 stjerner):</p>
                                1 <input type="radio" name="'.$this->prefixId.'[rating]" value="1">
                                <input type="radio" name="'.$this->prefixId.'[rating]" value="2">
                                <input type="radio" name="'.$this->prefixId.'[rating]" value="3">
                                <input type="radio" name="'.$this->prefixId.'[rating]" value="4">
                                <input type="radio" name="'.$this->prefixId.'[rating]" value="5"> 5
								&nbsp;<input type="checkbox" name="'.$this->prefixId.'[report_error]">Rapportér fejl</input>
                                <br/>
                                
                                <input type="submit" name="'.$this->prefixId.'[saveComment]" value="Send kommentar">

                        </form><br/><br/>';
                
                
                
                
                $content ='<form action="'.t3lib_div::getIndpEnv('REQUEST_URI').'" method="POST">
                        <input type="hidden" name="no_cache" value="1">
                        
                        <table border="0" style=" width:700px; margin-top: 18px">
                                <tr>
                                <td>'.($this->piVars['returnUrl']?'<p><a href="'.htmlspecialchars($this->piVars['returnUrl']).'">&lt; Tilbage til dagsorden</a></p>':'').'</td>
                                <td valign="top" align="right">
                        <img src="typo3conf/ext/enotelms/icons/done'.(!$record['userdata'][0]['done']?'_d':'').'.png" width="20" height="24" align="absmiddle"/>'.
                                (!$record['userdata'][0]['done'] ? '<input type="submit" name="'.$this->prefixId.'[done]" value="Afkryds" />' : '<input type="submit" name="'.$this->prefixId.'[undone]" value="Fjern afkrydsning" />').'
                &nbsp; &nbsp; &nbsp;<img src="typo3conf/ext/enotelms/icons/heart'.(!$record['userdata'][0]['fav']?'_d':'').'.png" width="20" height="12" align="absmiddle" />'.
                                (!$record['userdata'][0]['fav'] ? '<input type="submit" name="'.$this->prefixId.'[fav]" value="Favorit" />' : '<input type="submit" name="'.$this->prefixId.'[unfav]" value="Fjern favorit" />').'
                                </td></tr></table>
                </form>'.$content;

                        return $content;
                }
        }
        
        function getMetaData($fileName) {
#               debug($fileName);       
                // TODO: Check incoming value that it is a proper file under site!!
#$fileName = 'fileadmin/TEST_podcast/studie/01005_Matematik1-Uge1_IntroTilLinearAlgebra.txt';           
                $match = array();
                if (preg_match('/^(.*)\.(-[[:alnum:]]+|)[[:alnum:]]+$/',$fileName,$match))      {
                        $fileAbsPath = t3lib_div::getFileAbsFileName($match[1].'.txt');
                        
                        if (!@is_file($fileAbsPath))    return FALSE;

#echo($fileAbsPath);
                        $fileContent = t3lib_div::getUrl($fileAbsPath);
#echo($fileContent);
                                // Parse meta data configuration file and do some processing:
                        $lines = t3lib_div::trimExplode(chr(10),$fileContent,1);
                        $info = array();
                        foreach($lines as $linecontent) {
                                if (substr($linecontent,0,1)!="#")      {
                                        list($fieldname, $value) = preg_split('/=/',$linecontent,2);
                                        $value = trim($value);
                                        $fieldname = trim($fieldname);
                                        if ($fieldname && $value && substr($value,0,1)!='[')    {
                                                $info[$fieldname] = $value;
                                        }
                                }
                        }       
                        if ($info['pubDate'])   {
                                $info['pubDate'] = mktime(substr($info['pubDate'],11,2), substr($info['pubDate'],14,2), 0, substr($info['pubDate'],5,2), substr($info['pubDate'],8,2) , substr($info['pubDate'],0,4));
                        } else {
                                $info['pubDate'] = filemtime($fileAbsPath);
                        }
                        
                        $baseAbsFileName=$match[1];
                                # Look up thumbnails:
                        for($a=0;$a<3;$a++)     {
                                $testName = $baseAbsFileName.'-'.($a+1);
                                if (@is_file($testName.'.png')) {
                                        $info['media']['thumbnail'][$a] = $testName.'.png';
                                } elseif (@is_file($testName.'.jpg'))   {
                                                $info['media']['thumbnail'][$a] = $testName.'.jpg';
                                } else {
                                        break;
                                }
                        }
                        
                }
                return $info;
#               debug($info);
#               exit;
        }
        
        function getAtomType($atomURL)  {
                if (t3lib_div::isFirstPartOfStr($atomURL,t3lib_div::getIndpEnv('TYPO3_SITE_URL').'fileadmin/podcast/'))    {
                        return array('type'=>'video','localFile'=>substr($atomURL,strlen(t3lib_div::getIndpEnv('TYPO3_SITE_URL'))));
                } elseif (t3lib_div::isFirstPartOfStr($atomURL,t3lib_div::getIndpEnv('TYPO3_SITE_URL').'fileadmin/MapleDemo'))     {
                        return array('type'=>'mapledemo');
                } elseif (t3lib_div::isFirstPartOfStr($atomURL,'materialer/enoter/afsnit/NUID6'))       {
                        return array('type'=>'enote','icon'=>'OPG','NUID'=>substr($atomURL,25,-1));
                } elseif (t3lib_div::isFirstPartOfStr($atomURL,'materialer/enoter/'))   {
                        return array('type'=>'enote','NUID'=>substr($atomURL,25,-1));
                } elseif (t3lib_div::isFirstPartOfStr($atomURL,'http://www.livescribe.com/cgi-bin/WebObjects/LDApp.woa/wa/MLSOverviewPage?sid='))   {
                        return array('type'=>'pencast');
                }
        }
        
        function labelNumberValue($NUID)        {
                $linkParts = explode('-',$NUID);
                if (!isset($this->cacheLabels[$linkParts[0]]))  {

                        preg_match('/^NUID([0-9]+)$/',$linkParts[0],$matches);

                        $data = unserialize(t3lib_div::getUrl(t3lib_div::getFileAbsFileName($this->enoteHTMLpath).$matches[1].'/index.html.ser'));
                        $this->cacheLabels[$linkParts[0]]=array();
                        foreach($data['structure']['documentParts'] as $theIdx => $part)        {
                                $this->cacheLabels[$linkParts[0]] = t3lib_div::array_merge($this->cacheLabels[$linkParts[0]],$part['labelsInside']);
                        }
                }
                return $this->cacheLabels[$linkParts[0]][$NUID];
        }
        function generateHideDropDown($typeBoxdivenv) {
			$this->count++;
			$content .= '<div class="boxhidelink">
							<a href="#" onClick="showOptionsMenu(\'hideMenu_'.$this->count.'\',\''.$typeBoxdivenv.'\',\''.$this->hidableBoxEnvs[$typeBoxdivenv].'\'); return false" onmouseout="startclosetimer(\'hideMenu_'.$this->count.'\')" onmouseover="stopclosetimer(\'hideMenu_'.$this->count.'\')">&#215;</a>
							<div class="hideDropDown" id=\'hideMenu_'.$this->count.'\' style="visibility:hidden" onmouseout="startclosetimer(\'hideMenu_'.$this->count.'\')" onmouseover="stopclosetimer(\'hideMenu_'.$this->count.'\')">
							</div>
						</div>';
			return $content;
		}
		
		// Retrieves all active elements (atoms) from an agenda (type==3)
		function getActiveElements($NUID) {
			$linkParts = explode('-',$NUID);
            preg_match('/^NUID([0-9]+)$/',$linkParts[0],$matches);
            $data = unserialize(t3lib_div::getUrl(t3lib_div::getFileAbsFileName($this->enoteHTMLpath).$matches[1].'/index.html.ser'));
            if (is_array($data))    {  
                  $structure = $data['structure'];
                  $structure = $this->filterStructure($structure,$linkParts);
				  $accum = $this->accumulateStructure($structure);


                          // Navigation:
#                       $content.= '<hr><p>';
#                       if (isset($structure['_previousIDX'])) $content.= ' | '.$this->pi_list_linkSingle('< PREV','NUID'.$data['eNoteRec']['uid'].'-IDX'.$structure['_previousIDX']);
#                       if (isset($structure['_nextIDX'])) $content.= ' | '.$this->pi_list_linkSingle('NEXT >','NUID'.$data['eNoteRec']['uid'].'-IDX'.$structure['_nextIDX']);
#                       $content.= '</p><hr>';

				if (is_array($structure)) {
					foreach($structure['documentParts'] as $s) {
						$HTML .= $s['HTML'];
					}
					$HTML = '<meta http-equiv="content-type" content="text/html; charset=utf-8">' . $HTML;
					$doc = new DOMDocument();
					$doc->strictErrorChecking = FALSE;
					$doc->loadHTML($HTML);
					$html = simplexml_import_dom($doc);
					if($html) {
						$links = $html->xpath("//a");
						$tempEnotes = Array();
						$agendaItems = Array('exercise' => array('title' => 'Opgaver'), 'video' => array('title' => 'Videoer og Pencast'), 'enote' => array('title'=>'eNoter'),'maple'=>array('title'=>'Mapledemoer'));
						foreach($links as $l) {
							
							$link = $l['href'];
							$matches = preg_split("/::/",$link);
							$value = $l;
							if(!preg_match("/^eNote/",$value)) {
								$value = ucfirst($value);
							}

							if (t3lib_div::inList('refA,trefA,threfA',$matches[0]))      {
                                    if (t3lib_div::inList('tref,refA,trefA',$matches[0]))   {
                                            $value=strip_tags($value).' '.$this->labelNumberValue($matches[1]);
                                    }
                                    $theLink =$this->pi_list_linkSingle(strip_tags($value),$matches[1],1);
                                    $theURL = $this->cObj->lastTypoLinkUrl;
                            } else {
                                    $theLink =      '<a href="'.htmlspecialchars($matches[1]).'">'.strip_tags($value).'</a>';
                                    $theURL = $matches[1];
                            }
                            if (t3lib_div::inList('refA,hrefA,trefA,threfA',$matches[0]) && $GLOBALS['TSFE']->loginUser)    {
                                    $ELOinfo = $this->getELAtom($theURL);
									$info = $this->getAtomType($theURL);
									
									if($info['type'] == 'enote') {
										$tempEnotes[] = array('ELOinfo' => $ELOinfo, 'info' => $info, 'link' => $theLink);
									} else {
										if($tempEnotes) {
											//$agendaItems['enote'] = array_merge($agendaItems['enote'], $tempEnotes);
											$enotePackage[] = $tempEnotes;
											$tempEnotes = array();
										}
										if($info['type'] == 'video' || $info['type'] == 'pencast') {
											$agendaItems['video'][] = Array('ELOinfo' => $ELOinfo, 'info' => $info, 'link' => $theLink);
										} elseif($info['type'] == 'mapledemo') {
											$agendaItems['maple'][] = Array('ELOinfo' => $ELOinfo, 'info' => $info, 'link' => $theLink);
										}
									}
									
                                    /*$content .= '<span style="'.($ELOinfo['userdata'][0]['done']?'':'border: solid #bbbbbb 1px;').' background-color: '.($ELOinfo['userdata'][0]['done']?'transparent':'#ffff99').';">'.
                                                    '<img src="typo3conf/ext/enotelms/icons/done'.(!$ELOinfo['userdata'][0]['done']?'_d':'').'.png" width="20" height="24" align="absmiddle"/>'.
                                                    ($ELOinfo['userdata'][0]['fav']?'<img src="typo3conf/ext/enotelms/icons/heart.png" width="12" height="12" align="absmiddle" />&nbsp;':'').
                                                    $this->pi_linkTP(strip_tags($theLink),Array($this->prefixId=>array('atom'=>$ELOinfo['uid'],'returnUrl'=>$this->piVars['returnUrl'])),1).
                                                    '('.$type['type'].')</span><br/>';*/
                            }
						}
						if($tempEnotes) {
							//$agendaItems['exercise'] = array_merge($agendaItems['exercise'],$tempEnotes);
							$enotePackage[] = $tempEnotes;
						}
						$i = 0;
						// Find the biggest chunk of eNote links in a row
						// That must be the exercises
						foreach($enotePackage as $id => $epack) {
							if(sizeof($epack) > sizeof($enotePackage[$i])) {
								$i = $id;
							}
						}
						$agendaItems['exercise'] = array_merge($agendaItems['exercise'],$enotePackage[$id]);
						unset($enotePackage[$id]);

						// Merge the leftover enote links, assign to "eNote" category
						foreach($enotePackage as $e) {
							$agendaItems['enote'] = array_merge($agendaItems['enote'], $e);
						}

						// SEPERATE LAYOUT
						/*foreach($agendaItems as $category => $struct) {
							$content .= '<div class="webpart"><div class="topbar"><span class="topBarTitle">'.$struct['title'].'</span></div><div class="inner"><div style="margin:10px 0 10px;">';
							foreach($struct as $key => $element) {
								if(is_numeric($key)) {								
									$content .= '<div style="border-bottom: 0px solid rgb(231, 235, 239); padding: 1px 10px 1px 10px; background-color: '.($this->ELAtom['uid'] == $element['ELOinfo']['uid'] ? '#EFDDED' : '').'"><div style="margin-left: 0px;"><img src="typo3conf/ext/enotelms/icons/done'.(!$element['ELOinfo']['userdata'][0]['done']?'_d':'').'.png" width="20" height="24" align="absmiddle" style="float: left"/><div style="padding: 2px 0 0 25px">'.$this->pi_linkTP(strip_tags($element['link']),Array($this->prefixId=>array('atom'=>$element['ELOinfo']['uid'],'returnUrl'=>$this->piVars['returnUrl'])),1).'</div><div style="clear:both"></div></div></div>';
								}
							}
							$content .= "</div></div></div><br/><br/>";
						}*/
						
						$content .= '<div class="webpart"><div class="topbar"><span class="topBarTitle">Dagsorden</span></div><div class="inner"><div style="margin:10px 0 10px;">';
						foreach($agendaItems as $category => $struct) {
							if(count($struct) == 1) continue;
							$content .= "<h4 style='margin-left: 10px'>".$struct['title']."</h4>";
							foreach($struct as $key => $element) {
								if(is_numeric($key)) {								
									$content .= '<div style="border-bottom: 0px solid rgb(231, 235, 239); padding: 1px 10px 1px 10px; background-color: '.($this->ELAtom['uid'] == $element['ELOinfo']['uid'] ? '#EDDF95' : '').'"><div style="margin-left: 0px;"><img src="typo3conf/ext/enotelms/icons/done'.(!$element['ELOinfo']['userdata'][0]['done']?'_d':'').'.png" width="20" height="24" align="absmiddle" style="float: left"/><div style="padding: 5px 0 5px 25px">'.$this->pi_linkTP(strip_tags($element['link']),Array($this->prefixId=>array('atom'=>$element['ELOinfo']['uid'],'returnUrl'=>($this->piVars['returnUrl']?$this->piVars['returnUrl']:t3lib_div::getIndpEnv('REQUEST_URI')))),1).'</div><div style="clear:both"></div></div></div>';
								}
							}
						}
						$content .= "</div></div></div><br/><br/>";
					}
				}
			}
			return $content;
		}
			
        function renderNUIDlink($NUID, $checkAtom=true)  {
                if ($GLOBALS['TSFE']->loginUser && $this->piVars['atom'])       {
                        $record = $this->getELAtomFromUid($this->piVars['atom']);

                        $quizAnswers = unserialize($record['userdata'][0]['data']);
                }
                $linkParts = explode('-',$NUID);
                preg_match('/^NUID([0-9]+)$/',$linkParts[0],$matches);
                
                $data = unserialize(t3lib_div::getUrl(t3lib_div::getFileAbsFileName($this->enoteHTMLpath).$matches[1].'/index.html.ser'));
				//echo "<div style='display: none'>" . print_r($data,true) . "</div>";
                $atom = $this->getELAtom(strtok($this->pi_list_linkSingle('',$NUID,1,0,1), "?"), false);
                if(!$this->piVars['atom'] && $atom && $checkAtom && $GLOBALS['TSFE']->loginUser) {
                	if($atom['disabled'] == 0) {
                		return $this->renderAtom($atom['uid']);
                	}
                }
                if (is_array($data))    {

                        /*$content =
                        '<div'.$this->pi_classParam('singleView').'>
                                <h1>'.($data['eNoteRec']['enote']?'eNote '.$data['eNoteRec']['enote'].': ':'').htmlspecialchars($data['eNoteRec']['title']).'</h1><br/>';*/

						// exercise collection
						if($data['enoteRec']['type'] == 1) {
							
						}
                        $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');       

                        $structure = $data['structure'];
                        $structure = $this->filterStructure($structure,$linkParts);

                        $accum = $this->accumulateStructure($structure);

        #debug($linkParts);



                                // Navigation:
#                       $content.= '<hr><p>';
#                       if (isset($structure['_previousIDX'])) $content.= ' | '.$this->pi_list_linkSingle('< PREV','NUID'.$data['eNoteRec']['uid'].'-IDX'.$structure['_previousIDX']);
#                       if (isset($structure['_nextIDX'])) $content.= ' | '.$this->pi_list_linkSingle('NEXT >','NUID'.$data['eNoteRec']['uid'].'-IDX'.$structure['_nextIDX']);
#                       $content.= '</p><hr>';

                        if (is_array($structure))       {
                                $tableRows=array();
								//echo "<div style='display: none'>".print_r(reset($structure['documentParts']))."</div>";
								$boxCount = 0;
								//$GLOBALS['TSFE']->additionalHeaderData[] = '<meta></meta>';
								// Set appropriate page title
								if($data['eNoteRec']['type'] == 0) {
									if($structure['documentParts'][0] || $structure['documentParts'][1]) {
										$GLOBALS['TSFE']->page['title'] = 'eNote ' . $data['eNoteRec']['enote'] . ': ' . $data['eNoteRec']['title'];
									} else {
										$firstPart = reset($structure['documentParts']);
										$doc = new DOMDocument();
									  	$doc->strictErrorChecking = FALSE;
									  	$doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>'.$firstPart['HTML']);
									  	$html = simplexml_import_dom($doc);
										//$html = new SimpleXMLElement($firstPart['HTML']);
										$title = array_shift($html->xpath("//*[name()='h1' or name()='h2' or name()='h3']"));
										if(!$title) {
											$title = '';
										}
										$GLOBALS['TSFE']->page['title'] = $title;
									}
								} else {
									$GLOBALS['TSFE']->page['title'] = $this->eNoteTypeNames[$data['eNoteRec']['type']];
								}
								
								if($data['eNoteRec']['enote']) {
									$content = '<div class="enote-header"><div class="box-title-lines"><div>&nbsp;</div></div>eNote '.$data['eNoteRec']['enote'] . '</h1></div>';
								}
                                foreach($structure['documentParts'] as $theIdx => $part)        {
										/*if(isset($part['HeaderLevel']) && $part['HeaderLevel'] == 0 && $data['eNoteRec']['enote']) {
											$content = '<div class="enote-header"><div class="box-title-lines"><div>&nbsp;</div></div>eNote '.$data['eNoteRec']['enote'] . '</h1></div>';
										}*/
                                        $HTML = $part['HTML'];
										if(!trim($HTML)) {
											continue;
										}
                                                // Prefixing relative paths:
                                        $HTML = $htmlParser->prefixResourcePath($this->enoteHTMLpath.$data['eNoteRec']['uid'].'/',$HTML);
                                        $HTML = str_replace('###NOTICE_ENV_ICON_PATH###','typo3conf/ext/enotelms/icons/note/',$HTML);
                                        $HTML = preg_replace('/Chapter \d+\./','',$HTML);               // TEMPORARY!!!

                                                // Processing A-tag for all links to IDs internally for this enote. Any links to other enotes are processed differently.:
                                        $blocks = $htmlParser->splitIntoBlock('a',$HTML);
                                        foreach($blocks as $k => $value){
                                                if (intval($k)%2)       {
                                                        
                                                                // Page links:
                                                        $matches = array();
                                                        preg_match('/href="\#([^"]+)"/' ,$value , $matches);
                                                        if (count($matches))    {
                                                                if (!in_array($matches[1],$accum['idsInside'])) {       // Is external...:
                                                                        $IDX = $structure['idIndex'][$matches[1]];
                                                                        $blocks[$k] = $this->pi_list_linkSingle(strip_tags($value),$linkParts[0].'-'.($IDX?'IDX'.$IDX:''),1);
#                                                                       debug(array($value,$blocks[$k],$matches,$IDX),'BEFORE-AFTER');
                                                                } else {
                                                                        $blocks[$k] = '<a href="'.t3lib_div::getIndpEnv('REQUEST_URI').'#'.$matches[1].'">'.strip_tags($value).'</a>';
                                                                }
                                                        }
                                                        
                                                        if (!count($matches))   {
                                                                        // External links:
                                                                $matches = array();
                                                                preg_match('/href="(tref|thref|refA|hrefA|trefA|threfA)::([^"]+)"/' ,$value , $matches);
                                                                if (count($matches))    {

                                                                                // Create links with internal references:
                                                                        if (t3lib_div::inList('tref,thref,refA,trefA,threfA',$matches[1]))      {
                                                                                if (t3lib_div::inList('tref,refA,trefA',$matches[1]))   {
                                                                                        $value=strip_tags($value).' '.$this->labelNumberValue($matches[2]);
                                                                                }
                                                                                $theLink =$this->pi_list_linkSingle(strip_tags($value),$matches[2],1);
                                                                                $theURL = $this->cObj->lastTypoLinkUrl;
                                                                        } else {
                                                                                $theLink =      '<a href="'.htmlspecialchars($matches[2]).'">'.strip_tags($value).'</a>';
                                                                                $theURL = $matches[2];
                                                                        }
                                                                        if (t3lib_div::inList('refA,hrefA,trefA,threfA',$matches[1]) && $GLOBALS['TSFE']->loginUser)    {
                                                                                $ELOinfo = $this->getELAtom($theURL, true);
                                                                                $blocks[$k] = '<span style="'.($ELOinfo['userdata'][0]['done']?'':'border: solid #bbbbbb 1px;').' background-color: '.($ELOinfo['userdata'][0]['done']?'transparent':'#ffff99').';">'.
                                                                                                '<img src="typo3conf/ext/enotelms/icons/done'.(!$ELOinfo['userdata'][0]['done']?'_d':'').'.png" width="20" height="24" align="absmiddle"/>'.
                                                                                                ($ELOinfo['userdata'][0]['fav']?'<img src="typo3conf/ext/enotelms/icons/heart.png" width="12" height="12" align="absmiddle" />&nbsp;':'').
                                                                                                $this->pi_linkTP(strip_tags($theLink),Array($this->prefixId=>array('atom'=>$ELOinfo['uid'],'returnUrl'=>t3lib_div::getIndpEnv('REQUEST_URI'))),1).
                                                                                                '</span>';
                                                                        } else {
                                                                                $blocks[$k] = $theLink;
                                                                        }
                                                                        
                                                                #       debug(array($value,$blocks[$k],$matches,$IDX,$theLink),'BEFORE-AFTER');
                                                                }
                                                        }
                                                }
                                        }
                                        
                                        $HTML = implode('',$blocks);
                                        // Use DOMXpath to parse the HTML
                                        $dom = new DOMDocument();
                                        // Add a <div></div> enclosing the content to please the pretty strict DOMDocument class
										$HTML = str_replace("&nbsp;","&#160;",$HTML);
										//Import HTML. Preferably as XML, but otherwise as HTML with some extra processing
                                        if(!$dom->loadXML("<div>".$HTML."</div>")){
											$dom->loadHTML('<?xml encoding="UTF-8"><div>' . $HTML . "</div>");
											// dirty fix
											foreach ($dom->childNodes as $item)
											    if ($item->nodeType == XML_PI_NODE)
											        $dom->removeChild($item); // remove hack
											$dom->encoding = 'UTF-8'; // insert proper
											$dom2 = new DOMDocument();
											$dom2->appendChild($dom2->importNode($dom->getElementsByTagName('body')->item(0)->firstChild, true));
											$dom = $dom2;
										}
                                        $xpath = new DOMXPath($dom);

										// Remove dot at the end of titles
										$titles = $xpath->query("//*[(self::h2 or self::h3 or self::h4) and contains(concat(' ',normalize-space(@class),' '),' title ')]");
										foreach($titles as $title) {
											$text = $title->firstChild->textContent;
											preg_match("/^((\d+\.)*\d+)(\.)/",$text,$matches);
											$title->firstChild->replaceData(0,strlen($matches[0]),$matches[1]);
										}
										
                                        $boxdivenvs = $xpath->query("//div[contains(@class,'boxdivenv')]");
                                        $vinkCount  = 0;
                                        $facitCount = 0;
                                        $quizCount  = 0;
 
                                        // Create a datastructure containing the relations of all dividers and noticeenvs to make processing easier afterwards
                                        $boxData = array();
                                        foreach($boxdivenvs as $boxdivenv) {
                                                $vinkCount = 0;
                                                $facitCount = 0;
												$boxCount++;
												$frag = $dom->createDocumentFragment();
												$frag->appendXML('<div class="box-title-lines"><div>&#xA0;</div></div>&#xA0;&#xA0;');
												$boxTitle = $xpath->query("//h3",$boxdivenv);
												$boxTitle->item(0)->insertBefore($frag,$boxTitle->item(0)->firstChild);
                                                preg_match("/boxdivenv\-(\w+)/",$boxdivenv->getAttribute("class"),$matches);
                                                $typeBoxdivenv = $matches[1];
												$boxdivenv->setAttribute('style','z-index: ' . (1000 - $boxCount));
												$boxdivenv->setAttribute('id','box_' . $boxCount);
                                                $boxData[] = array('type' => $typeBoxdivenv, 'element' => $boxdivenv, 'noticeenvs' => array(), 'questions' => array());
												// Do not show hiding options (or hide box) if it is the only element
												if(count($structure['documentParts']) > 1) {
													$showLink = $dom->createElement('a');
													$showLink->setAttribute("class", "showBoxLink");
													$showLink->setAttribute("style","display: none");
													$showLink->setAttribute("id","hideLink_".$boxCount);
													$showLink->setAttribute("href", "#");
													$showLink->setAttribute("onClick","showBox(".$boxCount."); return false");
													$showLink->appendChild($dom->createTextNode("Vis ".$this->hidableBoxEnvs[$typeBoxdivenv]));

													$boxdivenv->parentNode->insertBefore($showLink, $boxdivenv->nextSibling);
												
													if(array_key_exists($typeBoxdivenv,$this->hidableBoxEnvs)) {
														$hideLink = $dom->createDocumentFragment();
														$hideLink->appendXML($this->generateHideDropDown($typeBoxdivenv));
														$boxdivenv->insertBefore($hideLink,$boxdivenv->firstChild);
													}
												
													$hiddenBoxEnvs = unserialize($this->userdata['hidden_boxenvs']);
													if(in_array($typeBoxdivenv,$hiddenBoxEnvs)) {
														$style = $boxdivenv->getAttribute('style');
														$boxdivenv->setAttribute('style',$style . '; display: none');
														$showLink->setAttribute("style","display: block");
													}
												}
												
												
												
                                                $noticeenvs = $xpath->query("//table[contains(@class,'noticeenv')]",$boxdivenv);
                                                foreach($noticeenvs as $noticeenv) {
                                                        preg_match("/noticeenv\-(\w+)/",$noticeenv->getAttribute("class"),$matches);
                                                        $typeNoticeenv = $matches[1];

                                                        if($typeNoticeenv == "QUESTION"){
                                                                
                                                                $boxData[count($boxData)-1]['questions'][] = array('element' => $noticeenv, 'noticeenvs' => array('all' => array()), 'type' => 'exercise',);
                                                        } else {
                                                                if($typeNoticeenv == "VINK" ) { $count = ++$vinkCount;}
                                                                if($typeNoticeenv == "FACIT") { $count = ++$facitCount;}
                                                                
                                                                if(sizeof($boxData[count($boxData)-1]['questions']) > 0) {
                                                                        if(!is_array($boxData[count($boxData)-1]['questions'][count($boxData[count($boxData)-1]['questions'])-1]['noticeenvs'][$typeNoticeEnv])) {
                                                                                $boxData[count($boxData)-1]['questions'][count($boxData[count($boxData)-1]['questions'])-1]['noticeenvs'][$typeNoticeEnv] = array();
                                                                        }
                                                                        $boxData[count($boxData)-1]['questions'][count($boxData[count($boxData)-1]['questions'])-1]['noticeenvs'][$typeNoticeenv][] = array('element' => $noticeenv, 'count' => $count); 
$boxData[count($boxData)-1]['questions'][count($boxData[count($boxData)-1]['questions'])-1]['noticeenvs']['all'][] = array('element' => $noticeenv, 'count' => $count); 
                                                                } else {
                                                                        if(!is_array($boxData[count($boxData)-1]['noticeenvs'][$typeNoticeenv])) {
                                                                                $boxData[count($boxData)-1]['noticeenvs'][$typeNoticeenv] = array();
                                                                        }
                                                                        $boxData[count($boxData)-1]['noticeenvs'][count($boxData[count($boxData)-1]['questions'])-1][$typeNoticeenv][] = array('element' => $noticeenv, 'count' => $count);
                                                                }
                                                        }
                                                }
                                        } 
                                        // Process the data structure created before
                                        foreach ($boxData as $dividerKey => $dividerData) {
                                                $quizzes = 0;
                                                foreach($dividerData['questions'] as $questionKey => $question) {
                                                        $quizData = array();
                                                        $possibleQuizzes = $xpath->query(".//div/*[self::ol or self::ul]",$question['element']);
                                                        foreach($possibleQuizzes as $quizKey => $quiz) {
                                                                $isValidQuiz = true;
                                                                $tempQuizData = array('question' => $question['element'],"options" => array(),"correctAnswers" => array(), 'quizType' => 'checkbox');
                                                                $elements = $xpath->query('li/div/p',$quiz);
                                                                $tempQuizData['quizNode'] = $quiz;
                                                                foreach($elements as $elementKey => $element) {
                                                                        if(preg_match("/^\s*\(\s*(\*|\*\s*\!|\s*)\s*\)/", $element->textContent, $ans) > 0) {
                                                                                $tempQuizData['options'][] = $element;
                                                                                if ($ansVal = trim($ans[1])) {
                                                                                        if (preg_match("/^\*$/",$ansVal) > 0) {
                                                                                                $tempQuizData['correctAnswers'][] = sizeof($tempQuizData['options']) - 1;
                                                                                        } elseif (preg_match("/^\*\s*\!$/",$ansVal) > 0) {
                                                                                                if (sizeof($tempQuizData['correctAnswers'])  == 0) {
                                                                                                        $tempQuizData['correctAnswers'][] = sizeof($tempQuizData['options']) - 1;
                                                                                                        $tempQuizData['quizType'] = 'radio';
                                                                                                } else { // Not a valid quiz
                                                                                                        $isValidQuiz = false;
                                                                                                        break;
                                                                                                }
                                                                                        }
                                                                                }
                                                                        } else { // Not a valid quiz
                                                                                $isValidQuiz = false;
                                                                                break;
                                                                        }
                                                                }
                                                                if ($isValidQuiz) {
                                                                        $quizData[] = $tempQuizData;
                                                                        $question['type'] = 'quizexercise';
                                                                } else {
                                                                        // Do something
                                                                }
                                                        }
                                                        
                                                        if($quizData) {
                                                                $quizzes++;
                                                        }
                                                        
														$vinkCountLocal = 0;
                                                        foreach($question['noticeenvs']['VINK'] as $vink) {
                                                                $vinkCountLocal++;
                                                                $p                      = $dom->createElement('p');
                                                                $vinkLink       = $dom->createElement('a','Giv mig vink #'.$vinkCountLocal);
                                                                $vinkDiv        = $dom->createElement('div');
                                                                $p->setAttribute("style", "font-size: 10px; font-style:italic; padding: 0 0 0 0; margin: 0 0 0 0; text-align: right;");
                                                                $vinkLink->setAttribute("href","#");
                                                                $vinkLink->setAttribute("onClick", "Effect.Appear('vinkcontent_".$theIdx."_".$vink['count']."');this.style.display='none';return false;");
                                                                $vinkDiv->setAttribute("style","display: none");
                                                                $vinkDiv->setAttribute("id", "vinkcontent_".$theIdx."_".$vink['count']);
                                                                $p->appendChild($vinkLink);
                                                                $vink['element']->parentNode->replaceChild($vinkDiv,$vink['element']);
                                                                $vinkDiv->appendChild($vink['element']);
                                                                $vinkDiv->parentNode->insertBefore($p,$vinkDiv);
                                                        }
														foreach($question['noticeenvs']['FACIT'] as $facit) {
																if ($question['type'] == 'exercise') {
                                                                        $p                      = $dom->createElement('p');
                                                                        $facitLink      = $dom->createElement('a','Vis facit');
                                                                        $facitDiv       = $dom->createElement('div');
                                                                        $p->setAttribute("style", "font-size: 10px; font-style:italic; padding: 0 0 0 0; margin: 0 0 0 0; text-align: right;");
                                                                        $facitLink->setAttribute("href","#");
                                                                        $facitLink->setAttribute("onClick", "Effect.Appear('facitcontent_".$theIdx."_".$facit['count']."');this.style.display='none';return false;");
                                                                        $facitDiv->setAttribute("style","display: none");
                                                                        $facitDiv->setAttribute("id", "facitcontent_".$theIdx."_".$facit['count']);
                                                                        $p->appendChild($facitLink);
                                                                        $facit['element']->parentNode->replaceChild($facitDiv,$facit['element']);
                                                                        $facitDiv->appendChild($facit['element']);
                                                                        $facitDiv->parentNode->insertBefore($p,$facitDiv);
                                                                } else if($question['type'] == 'quizexercise') {
                                                                        $p = $dom->createElement('p');
                                                                        $facitDiv = $dom->createElement('div');
                                                                        $p->setAttribute("style", "font-size: 10px; font-style:italic; padding: 0 0 0 0; margin: 0 0 0 0; text-align: right;");
                                                                        foreach($quizData as $index => $q){
                                                                                if($q['question']->isSameNode($question['element'])) {
                                                                                        if(!$quizAnswers[$theIdx][$quizzes]) {
                                                                                            $facitDiv->setAttribute("style","display: none");
                                                                                        }
                                                                                }
                                                                        }
                                                                        $facitDiv->setAttribute("id", "facitcontent_".$theIdx."_".$facit['count']);
                                                                        $facit['element']->parentNode->replaceChild($facitDiv,$facit['element']);
                                                                        $facitDiv->appendChild($facit['element']);
                                                                        $facitDiv->parentNode->insertBefore($p,$facitDiv);
                                                                        $quizFacitID[$quizCount] = 'facitcontent_'.$theIdx.'_'.$facit['count'];
                                                                }
                                                        }

                                                        

                                                        // Parse $quizData and make necessary substitutions
                                                        if(sizeof($quizData) > 0) {
                                                                $quizCount++;
                                                                $formElement = $dom->createElement('form');
                                                                $formElement->setAttribute('name',"form_".$theIdx."_".$quizCount);
                                                                $question['element']->parentNode->appendChild($formElement);
                                                                $formElement->appendChild($question['element']);
                                                                $question['element'] = $formElement;
                                                                $contentCell = $xpath->query(".//td[contains(@class,'contentcell')]",$formElement)->item(0);
                                                                $facitElement = '';
                                                                if($question['noticeenvs']['FACIT']) {
																		$facitElement = "facitcontent_".$theIdx."_" . $question['noticeenvs']['FACIT'][count($question['noticeenvs']['FACIT'])-1]['count'];
                                                                        $facitDivAppear = "Effect.Appear('" . $facitElement .  "')";
                                                                }
                                                                
                                                                if(!$quizAnswers[$theIdx][$quizCount]) {
                                                                        if($question['noticeenvs']['FACIT']) {
                                                                                $submitLocation = $question['noticeenvs']['FACIT'][count($question['noticeenvs']['FACIT']) -1]['element'];
                                                                                $submitLocation = $submitLocation->parentNode;
                                                                        } else if ($question['noticeenvs']['VINK']) {
                                                                                $submitLocation = $question['noticeenvs']['VINK'][count($question['noticeenvs']['VINK']) -1]['element'];
                                                                                $submitLocation = $submitLocation->parentNode;
                                                                        } else {
                                                                                $submitLocation = $formElement;
                                                                        }
                                                                
                                                                        $p = $dom->createElement('p');
                                                                        $p->setAttribute('style','font-size: 10px; font-weight: bold; padding: 0 0 0 0; margin: 5px 0 0 0; text-align: right;');
                                                                        $link = $p->appendChild($dom->createElement('a','Tjek svar'));
                                                                        $submitButton = $submitLocation->parentNode->appendChild($p);
                                                                        $link->setAttribute('href','#');
                                                                        $submitButton->setAttribute("onClick","quizFormCheck(document.form_".$theIdx."_". $quizCount .($facitElement?",'".$facitElement."'":"") ."); this.style.display='none';" . ($question['noticeenvs']['FACIT'] ?$facitDivAppear . ";" : "")." return false;");
                                                                }
                                                                

                                                                foreach($quizData as $count => $quiz) {
                                                                        if($quizAnswers[$theIdx][$quizCount][$count+1]) {
                                                                                $localAnswers = $quizAnswers[$theIdx][$quizCount][$count+1];
                                                                        } else {
                                                                                $localAnswers = '';
                                                                        }
                                                                        foreach($quiz['options'] as $countLocal => $optionElement) {
                                                                                $quizChoiceElement = $dom->createElement('input');
                                                                                $optionElement->parentNode->replaceChild($quizChoiceElement,$optionElement);
                                                                                $statusDiv = $quizChoiceElement->parentNode->insertBefore($dom->createElement('div','→'),$quizChoiceElement);
                                                                                if(in_array($countLocal, $quiz['correctAnswers']) && $localAnswers[$countLocal+1]) {
                                                                                        $statusDiv->setAttribute('style','font-size:20pt; display:inline; margin-right: 30px');
                                                                                } else {
                                                                                        $statusDiv->setAttribute('style','font-size:20pt; display:inline; visibility: hidden; margin-right: 30px');
                                                                                }
                                                                                $quizChoiceElement->setAttribute("type",$quiz['quizType']);
                                                                                $quizChoiceElement->setAttribute("name","option[".$theIdx."][".$quizCount."][".($count+1)."]");
                                                                                $quizChoiceElement->setAttribute("value", $countLocal+1);
                                                                                $quizChoiceElement->setAttribute("alt", (in_array($countLocal,$quiz['correctAnswers']) ? 'y' : ''));
                                                                                if($localAnswers[$countLocal+1] == 'true') {
                                                                                        $quizChoiceElement->setAttribute('checked','checked');
                                                                                }
                                                                                if($localAnswers) {
                                                                                        $quizChoiceElement->setAttribute('disabled','disabled');
                                                                                }
                                                                                $quizChoiceElement->setAttribute("style","margin-left: -25px");
                                                                                $optionHTML = $dom->saveXML($optionElement);
                                                                                $optionHTML = preg_replace("/(<p>)\s*\(\s*(\*\s*\!?|)\s*\)\s*/","$1",$optionHTML);
                                                                                $optionChunk = $dom->createDocumentFragment();
                                                                                $optionChunk->appendXML($optionHTML);
                                                                                $quizChoiceElement->appendChild($optionChunk);
                                                                                $quizChoiceElement->lastChild->setAttribute("style","display: inline; padding-top: 0px; padding-left: 5px;");
                                                                        }
                                                                    $quiz['quizNode']->setAttribute('style','list-style-type: none; padding-left: 0px');
                                                                }
                                                                
                                                                $answer = '';
                                                                if($quizAnswers[$theIdx][$quizCount]) {
                                                                        $answer = 'correct';
                                                                        foreach($quizAnswers[$theIdx][$quizCount] as $index => $subquiz) {
                                                                                foreach ($subquiz as $subindex => $option) {
                                                                                        if(in_array($subindex-1,$quizData[$index-1]['correctAnswers'])) {
                                                                                                if($option == "false") {
                                                                                                        $answer = 'wrong';
                                                                                                }
                                                                                        } else {
                                                                                                if($option == "true") {
                                                                                                        $answer = 'wrong';
                                                                                                }
                                                                                        }
                                                                                }
                                                                        }
                                                                }
                                                                
                                                                $correct = $dom->createDocumentFragment();
                                                                $wrong   = $dom->createDocumentFragment();
                                                                
                                                                $correct->appendXML('<b>Svaret er <span style="color: green">rigtigt!</span></b>');
                                                                $wrong->appendXML('<b>Svaret er <span style="color: red">forkert!</span> De rigtige svar er markeret med pile ovenfor.</b>');
                                                                
                                                                $resultDivCorrect = $contentCell->appendChild($dom->createElement('div',' '));
                                                                $resultDivCorrect->appendChild($correct);
                                                                $resultDivCorrect->setAttribute('id',"result_correct_form_".$theIdx."_".$quizCount);
                                                                $resultDivCorrect->setAttribute('style','display:' . ($answer=='correct' && !$question['noticeenvs']['FACIT'] ? 'block' : 'none'));
                                                                $resultDivWrong = $contentCell->appendChild($dom->createElement('div',' '));
                                                                $resultDivWrong->appendChild($wrong);
                                                                $resultDivWrong->setAttribute('id',"result_wrong_form_".$theIdx."_".$quizCount);
                                                                $resultDivWrong->setAttribute('style','display:'. ($answer == 'wrong' && !$question['noticeenvs']['FACIT'] ? 'block' : 'none'));
																if($answer == 'wrong') {
																	if($question['noticeenvs']['FACIT'][count($question['noticeenvs']['FACIT']) - 1]['element']) {
																		$facit = $question['noticeenvs']['FACIT'][count($question['noticeenvs']['FACIT']) - 1]['element'];
																		$img = $xpath->query('.//div[contains(@class,"iconcell")]/img',$facit);
																		$img->item(0)->setAttribute('src',"typo3conf/ext/enotelms/icons/note/wrong.png");
																	}
																}
                                                        }
                                                       
                                                        
                                                        // Put question into labeled div
                                                        $questionDiv = $dom->createElement('div');
							$questionDiv->setAttribute('class','question-outer-container-'.$theIdx);
							
							if($questionKey != 0 && $dividerData['type'] == 'quizexercisebegin') {
							        $questionDiv->setAttribute("style","display: none");
							}
                                                        $questionContainer = $question['element']->parentNode;
                                                        $questionContainer->setAttribute('class','question-inner-container');
                                                        $parentNode = $questionContainer->parentNode;
                                                        $firstChild = $questionContainer->parentNode->firstChild->nextSibling;
                                                        $previousDiv = $questionContainer;
                                                        
                                                        while(get_class(($previousDiv = $previousDiv->previousSibling)) == 'DOMText');
                                                        $newDiv = $questionDiv->appendChild($questionContainer);
                                                        if($previousDiv != NULL) {
                                                                while (true) {
                                                                        $oldPreviousDiv = $newDiv;
                                                                        if(! $firstChild->isSameNode($previousDiv)) {
                                                                                        if($previousDiv->getAttribute('class') != "question-inner-container") {
                                                                                                $tempDiv = $previousDiv;
                                                                                                while(get_class($previousDiv = $previousDiv->previousSibling) == 'DOMText');
                                                                                                $newDiv = $questionDiv->insertBefore($tempDiv,$oldPreviousDiv);
                                                                                        } else {break;}
                                                                        } else {break;}
                                                                }
                                                        }

														foreach($question['noticeenvs']['all'] as $notice) {
                                                                $questionDiv->appendChild($notice['element']->parentNode->parentNode);
                                                        }
                                                        
                                                        $parentNode->appendChild($questionDiv);
                                                        if ($questionKey == 0 && $dividerData['type'] == 'quizexercisebegin') {
                                                                $progress = $dom->createDocumentFragment();
                                                                $progress->appendXML("<div style='font-weight: bold; margin-top: 20px'>Spørgsmål <span id='quiz-progress-".$theIdx."'>1</span> af " . count($dividerData['questions']) . "</div>");
                                                                $parentNode->insertBefore($progress, $questionDiv);
                                                        }
                                                        if($questionKey == count($dividerData['questions'])-1 && $dividerData['type'] == 'quizexercisebegin') {
                                                                $buttons = $dom->createDocumentFragment();
                                                                $buttons->appendXML("<div style='overflow: hidden; margin: 10px 0 0 0'><div style='width: 50%; float: left; visibility: hidden' id='previous-question-button-".$theIdx."'><a href='#' onClick='previousQuestion(".$theIdx."); return false'>Tilbage</a></div><div id='next-question-button-".$theIdx."' style='width:50%; float: right; text-align: right; visibility: " .(count($dividerData['questions']) > 1 ? 'visible' : 'hidden'). "'><a href='#' onClick='nextQuestion(".$theIdx."); return false'>Frem</a></div></div>");
                                                                $parentNode->appendChild($buttons);
                                                                //$parentNode->parentNode->insertBefore($buttons,$parentNode);
                                                                //$parentNode->insertBefore($buttons,$questionDiv);
                                                        }


                                                }
                                                foreach($dividerData['noticeenvs'] as $noticeenv){
                                                        // This is where noticeenvironments NOT linked to a question-environment should be treated
                                                        // For most of the simple environments, no action should be taken here, as CSS handles the
                                                        // Necessary formatting. If one for some reason wanted VINK and FACIT to be supported any-
                                                        // where, this is the place to do the implementation.
														/* 
														$vinkCountLocal = 0;
                                                        foreach($noticeenv['VINK'] as $vink) {
	                                                        $vinkCountLocal++;
	                                                        $p                      = $dom->createElement('p');
	                                                        $vinkLink       = $dom->createElement('a','Giv mig vink #'.$vinkCountLocal);
	                                                        $vinkDiv        = $dom->createElement('div');
	                                                        $p->setAttribute("style", "font-size: 10px; font-style:italic; padding: 0 0 0 0; margin: 0 0 0 0; text-align: right;");
	                                                        $vinkLink->setAttribute("href","#");
	                                                        $vinkLink->setAttribute("onClick", "Effect.Appear('vinkcontent_".$theIdx."_".$vink['count']."');this.style.display='none';return false;");
	                                                        $vinkDiv->setAttribute("style","display: none");
	                                                        $vinkDiv->setAttribute("id", "vinkcontent_".$theIdx."_".$vink['count']);
	                                                        $p->appendChild($vinkLink);
	                                                        $vink['element']->parentNode->replaceChild($vinkDiv,$vink['element']);
	                                                        $vinkDiv->appendChild($vink['element']);
	                                                        $vinkDiv->parentNode->insertBefore($p,$vinkDiv);
                                                        }
														foreach($noticeenv['FACIT'] as $facit) {
	                                                        $p                      = $dom->createElement('p');
	                                                        $facitLink      = $dom->createElement('a','Vis facit');
	                                                        $facitDiv       = $dom->createElement('div');
	                                                        $p->setAttribute("style", "font-size: 10px; font-style:italic; padding: 0 0 0 0; margin: 0 0 0 0; text-align: right;");
	                                                        $facitLink->setAttribute("href","#");
	                                                        $facitLink->setAttribute("onClick", "Effect.Appear('facitcontent_".$theIdx."_".$facit['count']."');this.style.display='none';return false;");
	                                                        $facitDiv->setAttribute("style","display: none");
	                                                        $facitDiv->setAttribute("id", "facitcontent_".$theIdx."_".$facit['count']);
	                                                        $p->appendChild($facitLink);
	                                                        $facit['element']->parentNode->replaceChild($facitDiv,$facit['element']);
	                                                        $facitDiv->appendChild($facit['element']);
	                                                        $facitDiv->parentNode->insertBefore($p,$facitDiv);
                                                        }*/

                                                }
                                        }
                                        
                                        // There is only ONE root node in $dom, as we enclosed the content in a <div></div> when importing
                                        // By exporting the child node explicitly, we avoid unnecessary <?xml ..  > tags
                                        //$HTML = $dom->saveXML($dom->childNodes->item(0));
                                        $HTML = $dom->saveXML($dom, LIBXML_NOEMPTYTAG); // TEMPORARY
										$HTML = preg_replace("/^<\?xml.*\?>/","", $HTML); // TEMPORARY 
                                        $HTML = $htmlParser->removeFirstAndLastTag($HTML);
                                        unset($part['HTML']);
                                        if(trim($HTML)) // Avoid unnecessary tags
                                                $tableRows[] = '<div class="enoteHTML">'.$HTML.'</div>';
                                }
                                $content.='
                                        <script type="text/javascript" language="javascript">
                                        		var count=0;
                                                var currentQ = Array();
												var maxImageWidth = 550;
												var boxhidelinkTO = {};
												var boxehidelinks = {};
												document.observe("dom:loaded", function() {
													Event.observe(window,"click",function(){
														$$("div.enoteHTML div.boxdivenv:not(:hover) > div.boxhidelink:not(:hover)").each(function(e){
															e.hide();
															e.select("div.hideDropDown").first().style.visibility = "hidden";
														});
														$$("div.enoteHTML div.boxdivenv:hover > div.boxhidelink:not(:hover)").each(function(e){
															e.select("div.hideDropDown").first().style.visibility = "hidden";
														});
													});
													
													hash = unescape(self.document.location.hash.substring(1));
													if ($(hash)) {
														$($(hash).parentNode).show();
													}
													//$$("div.enoteHTML div.boxdivenv > div.boxhidelink > a").each(function(e){
													//	Event.observe(e, "click", function(){
													//		var dropDown = this.select("div.hideDropDown").first();
													//		if(e.select("div.hideDropDown").first().style.visibility == "visible") {
													//			e.select("div.hideDropDown").first().style.visibility = "hidden";
													//		} else {
													//			dropDown.style.visibility = "visible";
													//		}
													//	});
													//});
													
													$$("div.enoteHTML img").each(function(e){
														width = e.width
														height = e.height
														if(e.width > maxImageWidth) {
															e.height = Math.round(e.height / (e.width / maxImageWidth))
															e.width = maxImageWidth
														}
													});
													$$("div.enoteHTML a:not([href=#])").each(function(e) {
														parts = e.href.split("#");
														if(parts.last().include("SSS")) {
															e.setAttribute("onClick", "$(\'"+parts.last()+"\').parentNode.show()");
														}
													});
													$$("div.enoteHTML div.boxdivenv").each(function(e){	
														if(e.select("div.boxhidelink").first()) {													
															e.observe("mouseover",function() {
																link = this.select("div.boxhidelink").first();
																if(boxhidelinkTO[this.id] != undefined) {
																	window.clearTimeout(boxhidelinkTO[this.id]);
																	delete boxhidelinkTO[this.id];
																}
																// Only allow one settings link at a time, because IE doesnt support ANYTHING
																if (navigator.appName=="Microsoft Internet Explorer") {
																	for (i in boxhidelinkTO) {
																		if(this.id != i) {
																			window.clearTimeout(boxhidelinkTO[i]);
																			delete boxhidelinkTO[i];
																			$(i).select("div.boxhidelink").first().hide();
																		}
																	}
																}
																link.style.display="block";
															});
															e.observe("mouseout",function() {
																link = this.select("div.boxhidelink").first();
																if(boxhidelinkTO[this.id] == undefined && link.style.display == "block") {
																	if(link.select("div.hideDropDown").first().style.visibility == "visible") {
																		if (navigator.appName=="Microsoft Internet Explorer") {
																			// IE doesnt support arguments passed in setTimeout.
																			// Too bad if you use such a lousy browser
																					boxid = this.id;
																					boxhidelinkTO[this.id] = window.setTimeout(function(){hideMenuLink(boxid)},1000);
																	 	} else {
																			boxhidelinkTO[this.id] = window.setTimeout(hideMenuLink,5000,[this.id]);
																		}
																	} else {
																		if (navigator.appName=="Microsoft Internet Explorer") {
																			// IE puts out mouseout events way too often causing flickering
																			boxid = this.id;
																			window.clearTimeout(boxhidelinkTO[this.id]);
																			boxhidelinkTO[this.id] = window.setTimeout(function(){hideMenuLink(boxid)},10);	
																		} else {
																			hideMenuLink(this.id);
																		}
																	}
																}
															});
														}
													});
												});
												function hideMenuLink(box_id){
													$$("#"+box_id+" div.boxhidelink").first().hide(); 
													delete boxhidelinkTO[box_id];
												}
												function showOptionsMenu(id,boxtype,boxname) {
													$$("div.hideDropDown").each(function(e){
														if(e.id != id) {
															e.up("div.boxhidelink").hide();
															e.style.visibility = "hidden";
														} else {
															if(e.style.visibility == "hidden") {
																e.style.visibility = "visible";
																new Ajax.Updater(e,"", {method: "get",
															parameters: "eID=tx_enotelms_ajax&function=getBoxMenu&boxtype=" + boxtype + "&boxname=" + boxname});
															} else {
																e.style.visibility = "hidden";
															}
														}
													});
												}
                                                function currentQuestion(idx) {
                                                        if(currentQ[idx]) {
                                                                return currentQ[idx];
                                                        } else {
                                                                return (currentQ[idx] = 0)
                                                        }
                                                }
                                                function numberQuestions(idx) {
                                                        return $$("div.question-outer-container-" + idx).length;
                                                }
                                                function nextQuestion(idx){
                                                        if($$("div.question-outer-container-" + idx)[currentQuestion(idx) + 1]){
                                                                $$("div.question-outer-container-" + idx)[currentQuestion(idx)].hide();
                                                                $$("div.question-outer-container-" + idx)[++currentQ[idx]].show();
                                                                $("previous-question-button-" + idx).style.visibility = "visible";
                                                                if (currentQuestion(idx) == numberQuestions(idx) - 1) {
                                                                    $("next-question-button-" + idx).style.visibility = "hidden";    
                                                                }
                                                                $("quiz-progress-" + idx).innerHTML = currentQuestion(idx)+1;
                                                                return currentQ[idx];
                                                        } else {
                                                                return false;
                                                        }
                                                }
                                                function previousQuestion(idx) {
                                                        if($$("div.question-outer-container-" + idx)[currentQuestion(idx) - 1]) {
                                                                $$("div.question-outer-container-" + idx)[currentQuestion(idx)].hide();
                                                                $$("div.question-outer-container-" + idx)[--currentQ[idx]].show();
                                                                $("next-question-button-" + idx).style.visibility = "visible";
                                                                if (currentQuestion(idx) == 0) {
                                                                    $("previous-question-button-" + idx).style.visibility = "hidden";    
                                                                }
                                                                $("quiz-progress-" + idx).innerHTML = currentQuestion(idx)+1;
                                                                return currentQ[idx];
                                                        } else {
                                                                return false;
                                                        }
                                                }
                                                
                                                function quizFormCheck(form,facit) {
                                                        formElements = form.elements
                                                        correctAnswer = true;
                                                        var checkedList = "";
                                                        for(var i=0;i<formElements.length;i++) {
                                                                if(formElements[i].type == "checkbox" || formElements[i].type == "radio") {
                                                                        formElements[i].disabled = true
                                                                        if(formElements[i].alt == "y") {
																				elem = formElements[i].parentNode.firstChild;
																				do {
																			        elem = elem.nextSibling;
																			    } while (elem && elem.nodeType != 1);
                                                                                elem.style.visibility="visible"
                                                                                if(formElements[i].checked == false) {
                                                                                        correctAnswer = false;
                                                                                }
                                                                        } else {
                                                                                if (formElements[i].checked == true) {
                                                                                        correctAnswer = false;
                                                                                }
                                                                        }
                                                                        checkedList = checkedList + formElements[i].name + "[" + formElements[i].value + "]" + "="+ formElements[i].checked + "&"
                                                                }
                                                        }
                                                        if (correctAnswer) {
																if(!facit){
                                                                document.getElementById("result_correct_" + form.name).style.display = "block";
																}
                                                        } else {
																if(!facit){
                                                                document.getElementById("result_wrong_" + form.name).style.display = "block";
																} else {
																$$(\'#\'+facit+\' table td.iconcell div.iconcell img\').first().src = "typo3conf/ext/enotelms/icons/note/wrong.png";
																 }
                                                        }
                                                        var AjaxRequest = new Ajax.Request("", {method: "get", parameters: "eID=tx_enotelms_ajax&function=submitQuiz&" + checkedList + "atom=" + "'. $this->piVars['atom'] .'"})
                                                }
												function hideBox(type,title,permanently,mode) {
													$$((".boxdivenv-"+type)).each(function(e){
														if(e.visible() && mode == "hide") {
															var num = e.id.split("_").last();
															$("hideLink_" + num).show();
															e.hide();	
														} else if(mode == "show") {
															var num = e.id.split("_").last();
															$("hideLink_" + num).hide();
															e.show();
														}
														hideDropDown = e.select("div.hideDropDown").first();
														hideDropDown.style.visibility = "hidden";
														hideDropDown.innerHTML = "";
													});
													if(permanently) {
														if(mode == "hide") {
															var AjaxRequest = new Ajax.Request("",{method: "get", parameters: "eID=tx_enotelms_ajax&function=submitHideBox&type=" + type});
														} else if(mode == "show") {
															var AjaxRequest = new Ajax.Request("",{method: "get", parameters: "eID=tx_enotelms_ajax&function=submitShowBox&type=" + type});
														}
													}
													
												}
												function showBox(e) {
													$("hideLink_"+e).hide();
													Effect.SlideDown("box_"+e);
												}
												function hidemenu(id) {
													document.getElementById(id).style.visibility="hidden";
												}
												closetimer = Array();
												function startclosetimer(id) {
													if (!closetimer[id] && document.getElementById(id).style.visibility == "visible") {
														closetimer[id] = window.setTimeout(function(){hidemenu(id)}, 5000);
													}
												}
												function stopclosetimer(id) {
													if(closetimer[id]) {
														window.clearTimeout(closetimer[id]);
														closetimer[id] = null;
													}
												}
                                        </script>
                                ';
                                $content.=implode('',$tableRows);
                        } else $content.=$structure;

                        return $content;
                } else {
                        return 'ERROR: Could not find eNote '.intval($matches[1]);
                }
        }
        function getAtomTitle($theUrl) {
        	$type = $this->getAtomType($theUrl);
        	if($type['type'] == 'enote') {
        		$linkParts = explode('-',$type['NUID']);
                preg_match('/^NUID([0-9]+)$/',$linkParts[0],$matches);
                
                $data = unserialize(t3lib_div::getUrl(t3lib_div::getFileAbsFileName($this->enoteHTMLpath).$matches[1].'/index.html.ser'));
                $htmlParser = t3lib_div::makeInstance('t3lib_parsehtml');       

                $structure = $data['structure'];
                $structure = $this->filterStructure($structure,$linkParts);

                $accum = $this->accumulateStructure($structure);
				if($structure['documentParts'][0] || $structure['documentParts'][1]) {
					$title = 'eNote ' . $data['eNoteRec']['enote'] . ': ' . $data['eNoteRec']['title'];
				} else {
					$firstPart = reset($structure['documentParts']);
					$doc = new DOMDocument();
				  	$doc->strictErrorChecking = FALSE;
				  	$doc->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>' .$firstPart['HTML']);
				  	$html = simplexml_import_dom($doc);
					//$html = new SimpleXMLElement($firstPart['HTML']);
					$title = array_shift($html->xpath("//*[name()='h1' or name()='h2' or name()='h3']"));
					if(!$title) {
						$title = '';
					}
				}
				//mb_detect_encoding($title,'UTF-8',true) == "UTF-8" ? '' : $title = utf8_encode($title);
                return $title;
        	} elseif($type['type'] == 'video') {
        		$metaData = $this->getMetaData($type['localFile']);
        		return $metaData['title'];
        	} elseif($type['type'] == "pencast") {
				$cookie = tempnam ("/tmp", "CURLCOOKIE");
				$ch = curl_init();
				curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
				curl_setopt( $ch, CURLOPT_URL, $theUrl);
				curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
				curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
				curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
				curl_setopt( $ch, CURLOPT_FAILONERROR, true);
				$result = curl_exec( $ch );
				curl_close ( $ch );
				if($result) {
					$livescribe = new DOMDocument();
					$livescribe->loadHTML($result);
					$link = $livescribe->getElementsByTagName('link');
					$meta = $livescribe->getElementsByTagName('meta');
					foreach($link as $l) {
						if($l->getAttribute("rel") == 'video_src') {
							$xmllink = $l->getAttribute('href');
						}
					}
					foreach($meta as $m) {
						$name = $m->getAttribute('name');
						if($name == 'title') {
							$title = $m->getAttribute('content');
						} elseif($name == 'description') {
							$desc = $m->getAttribute('content');
							if(!trim($desc)) {$desc = "<span style='color:#ccc'>(Ingen beskrivelse)</span>";}
						}
					}
				}
				unlink($cookie);
				$linkparts = preg_split('/=/',$record['url']);
				$parts = preg_split('/path/',$xmllink);
				
				if($xmllink && $parts[1]) {
					return $title;
				}
			} elseif($type['type'] == 'mapledemo') {
				preg_match("/\/([^\/]+)$/", $theUrl, $m);
				if($m[1]) {
					return $m[1];
				}
        	}
        	return '['.$theUrl.']';
        }
        function getELAtom($theURL, $create=true)     {
                global $TYPO3_DB;

                
                $res = $TYPO3_DB->exec_SELECTgetRows('*','tx_enotelms_atom','pid='.intval($this->atomUID).' AND urlhash='.$TYPO3_DB->fullQuoteStr(md5($theURL),'tx_enotelms_atom'));

                //echo $this->piVars['returnUrl'];
                if(preg_match("/NUID(\d+)-IDX(\d+)/",$this->piVars['returnUrl'], $matches)){
                	$NUID = $matches[1];
                	$IDX  = $matches[2];
                }

                if (count($res))        {
                		if($this->piVars['TEST']==="1") {
                			$atoms = $TYPO3_DB->exec_SELECTgetRows('*','tx_enotelms_atom','','');
                			foreach($atoms as $atom) {
                				$field_values = array("title" => $this->getAtomTitle($atom['url']));
                				$TYPO3_DB->exec_UPDATEquery('tx_enotelms_atom','uid='.$atom['uid'], $field_values);
                			}
                			$field_values = array("title" => $this->getAtomTitle($theURL));
                			$TYPO3_DB->exec_UPDATEquery('tx_enotelms_atom','pid='.intval($this->atomUID).' AND urlhash='.$TYPO3_DB->fullQuoteStr(md5($theURL)), $field_values);
                		}

                        $record = $res[0];
                        $refererID = $record['refererID'];
                        if(!$refererID && $NUID && $IDX) {
                        	$field_values = array(
                        			'refererID' => 'NUID' . $NUID . '-IDX' . $IDX
                        		);
                        	$TYPO3_DB->exec_UPDATEquery('tx_enotelms_atom','pid='.intval($this->atomUID).' AND urlhash='.$TYPO3_DB->fullQuoteStr(md5($theURL)), $field_values);
                        }

                } elseif($create === true) {
                        $field_values = array(
                                'title' => $this->getAtomTitle($theURL),
                                'url' => $theURL,
                                'urlhash' => md5($theURL),
                                'pid' => $this->atomUID
                        );
                        if($NUID && $IDX) {
                        	$field_values['refererID'] = 'NUID' . $NUID . '-IDX' . $IDX;
                        }
                        $TYPO3_DB->exec_INSERTquery('tx_enotelms_atom',$field_values);
                        $res = $TYPO3_DB->exec_SELECTgetRows('*','tx_enotelms_atom','pid='.intval($this->atomUID).' AND urlhash='.$TYPO3_DB->fullQuoteStr(md5($theURL),'tx_enotelms_atom'));
                        if (count($res))        {
                                $record = $res[0];
                        } else {
                                debug('CRAP somethings wrong!');
                        }
                } else {
                	return false;
                }

                return $this->getELAtom_addUserData($record);
        }

        function getELAtomFromUid($theUID)      {
                global $TYPO3_DB;

                $res = $TYPO3_DB->exec_SELECTgetRows('*','tx_enotelms_atom','uid='.intval($theUID));

                if (count($res))        {
                        $record = $res[0];
                }
                
                return $this->getELAtom_addUserData($record);
        }
        
        function getELAtom_addUserData($record) {
                global $TYPO3_DB;
                        
                if (is_array($record) && $GLOBALS['TSFE']->loginUser)   {
                        $record['userdata'] = $TYPO3_DB->exec_SELECTgetRows('*','tx_enotelms_atom_userdata','atom_id='.intval($record['uid']).' AND crfeuser_id='.intval($GLOBALS['TSFE']->fe_user->user['uid']));
                }
#debug($record);
#debug($GLOBALS['TSFE']->fe_user->user['uid'],'fe user uid');
                
                return $record;
        }


        // KOPI fra enoteserver... 
                function filterStructure($structure,$linkParts) {

                        if (!$linkParts[1])     return $structure;      // If nothing but "NUID[UID]" is passed, all is to be shown

                        if (is_array($structure['documentParts']))      {
                                $newStructure = array();
                                $inside = FALSE;
                                $headerLevel = 0;
        #debug($structure['documentParts']);
        
                                        // Traverse structure:
                                foreach($structure['documentParts'] as $theIdx => $part)        {
                                        if ($inside)    {
                                                        // ... or if no ending label is given, look for the next section on the same HeaderLevel:
                                                if (!$linkParts[2] && (($part['HeaderLevel'] && $part['HeaderLevel'] <= $headerLevel) || !isset($headerLevel)))      {
                                                        break;
                                                }
                                        }
                                                // Looking for the "start":
                                        if (!$inside && $linkParts[1] && (in_array($linkParts[0].'-'.$linkParts[1],array_keys($part['labelsInside'])) || 'IDX'.$theIdx==$linkParts[1])) {
                                                $inside = TRUE; // Indicates, that we are now accumulating content - we are "inside" the linked section.
												$headerLevel = $part['HeaderLevel'];
                                        }

                                        if ($inside)    {
                                                        // If "inside", add the section:
                                                $newStructure[$theIdx] = $part;

                                                        // If only one section is to be shown, we break here.
                                                if (isset($linkParts[2]) && !trim($linkParts[2]))       break;  

                                                        // ... otherwise, look for the ending label if given:
                                                if ($linkParts[2] && (in_array($linkParts[0].'-'.$linkParts[2],array_keys($part['labelsInside'])) || 'IDX'.$theIdx==$linkParts[2]))     {
                                                        break;
                                                }
                                                
                                        } else {
                                                $structure['_previousIDX'] = $theIdx;
                                        }
                                }
                                $structure['_nextIDX'] = key($structure['documentParts']);
                                if (!$structure['_nextIDX'])    unset($structure['_nextIDX']);

                                $subtract = t3lib_div::intInRange($linkParts[3],0,10);
                                if ($subtract)  {
                                        for ($a=0;$a<$subtract;$a++)    {
                                                array_pop($newStructure);
                                        }
                                }
                                $structure['documentParts'] = $newStructure;
                                return $structure;
                        }
                }

                function accumulateStructure($structure)        {
                        $accum = array('labelsInside'=>array(),'idsInside'=>array());

                        foreach($structure['documentParts'] as $theIdx => $part)        {
                                $accum['labelsInside'] = t3lib_div::array_merge($accum['labelsInside'],$part['labelsInside']);
                                //$accum['HTML'].= $part['HTML'];
                                $accum['idsInside'] = array_merge($accum['idsInside'],$part['idsInside']);
                        }
                        return $accum;
                }       
}

if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/enotelms/pi1/class.tx_enotelms_pi1.php'])      {
        include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/enotelms/pi1/class.tx_enotelms_pi1.php']);
}

?>